Observed with Angular2 object

In the beginning, I want to apologize for my poor English. We are building the service of my recreation service. On the client side, it supports angular2. I am new to this technology. I read that it is better to use Observable instead of a promise. I want to get one object with user data, and, unfortunately, the console returns the error "Unable to read property ... from undefined". In the Angular documentation, the example uses an array, not a single object. When I use an array, there is no error, but I need to load one object. My question is, is the Observable get object and show object in the template?

** service **

import { Injectable } from "@angular/core";
import { AppParameters } from "../parameters";
import { AuthHttp } from "angular2-jwt";
import { AuthService } from "./auth.service";
import { Response } from "@angular/http";
import { Observable } from 'rxjs/Observable';
import { UsersModel } from "../../models/models";
import { GroupModel } from "../../models/models";

@Injectable()

export class ProfileService {

    private userUrl: string = AppParameters.ENDPOINT_URL + "/users";
    private groupUrl: string = AppParameters.ENDPOINT_URL + '/groups';
    private wallUrl: string = AppParameters.ENDPOINT_URL + "/posts/";


    constructor(
        private authHttp: AuthHttp,
        private authService: AuthService
    ){}

    getUsers(id) : Observable<UsersModel> {
            return this.authHttp.get(this.userUrl + '/' + id + '/')
                .map(this.extractData)
                .catch(this.handleError)
    }

    private extractData(res: Response) {
        let body = res.json();
        return body.data || { };
    }

    private handleError (error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}

** component **

import { Component, OnInit } from "@angular/core";
import { AppParameters } from "../../shared/parameters";
import { ProfileConfig } from "./profile.config";
import { UsersModel } from "../../models/models";
import { ProfileService } from "../../shared/services/profile.service";
import { ActivatedRoute } from "@angular/router";


@Component({
    templateUrl: AppParameters.TEMPLATE_URL + ProfileConfig.COMPONENT_NAME + '/user.html',
    providers: [ ProfileService ]
})

export class UserComponent implements OnInit {

    user : number;
    data: UsersModel;
    errorMessage: string;

    constructor(
        private profileService: ProfileService,
        private route: ActivatedRoute,
    ){}

    ngOnInit() {
        this.getUser();
        this.getData();
    }

    getUser() {
        this.route.params
            .subscribe(params => {
                this.user =+ params['id'];
            });
    }

    getData() {
        this.profileService.getUsers(this.user)
            .subscribe(
                data => this.data = data,
                error => this.errorMessage = <any>error
            );
    }
}

model

export class UsersModel {
    id: number;
    username: string;
    email: string;
    user_profile: UserProfileModel;
}

class UserProfileModel {
    city: string;
    status: string;
    about: string;
}
+4
4

() , .

// component
observer.subscribe(
   value => this.obj = value,
   (errData) => { this.renderErrors() },
   () => {
       this.variableFilledWhenDone = true;
   }
);

<!-- template -->
<div *ngIf="ariableFilledWhenDone">
       <!-- stuff that needs to happen async -->
    <div>
+1

, :

ngOnInit() {
    this.route.params
        .subscribe(params => {
            // route parameter changed.. lets get new data !
            this.user =+ params['id'];
            this.getData(); // do it here, cause NOW you have that id..
        });
}
0
<h3>Hello {{ data.username }}</h3>

<p>Change yours personal data</p>

<set-user-data [data] = 'data'></set-user-data>
0
source

I have found a solution. In the future, if someone was looking

private extractData(res: Response) {
    let body = <UsersModel>res.json();
    return body || { };
}
0
source

Source: https://habr.com/ru/post/1655316/


All Articles