一開始我想爲我可憐的英語道歉。我們建立了我的工作休息服務。在客戶端它支持angular2。我是這項技術的初學者。我讀過使用Observable更好,而不是承諾。我想用用戶數據來獲取單個對象,不幸的是,控制檯返回一個錯誤「無法讀取未定義的屬性...」。文檔Angular示例使用數組而不是單個對象。當我使用數組時,沒有錯誤,但我需要下載一個對象。我的問題是,無論是通過Observable獲取對象並在模板中顯示對象?可用對象Angular2觀察
** **服務
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);
}
}
** **成分
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
);
}
}
模式
export class UsersModel {
id: number;
username: string;
email: string;
user_profile: UserProfileModel;
}
class UserProfileModel {
city: string;
status: string;
about: string;
}
至於get屬性不是來自表格,而是使用Observable對象。 –
什麼表?請澄清你的問題..不要立即得到你的實際問題..在哪一點你得到這個錯誤信息?發佈完整的錯誤信息請。 – mxii
Eh。對不起,這個錯誤。文檔Angular數據從模型數組中獲取,我需要從對象中獲取它們。 –