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;
}