用对象Angular2观察

时间:2016-09-21 11:25:29

标签: angular observable angular2-http

一开始我想为我可怜的英语道歉。我们建立了我的工作休息服务。在客户端,它支持angular2。我是这项技术的初学者。我读到最好使用Observable而不是promise。我想获得一个包含用户数据的对象,不幸的是,控制台返回错误“无法读取属性...未定义”。文档Angular示例使用数组而不是单个对象。当我使用数组时,没有错误,但我需要下载一个对象。我的问题是,是否由Observable获取对象并在模板中显示对象?

**服务**

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

4 个答案:

答案 0 :(得分:1)

您可以在此处使用()完整功能,并在观察者完成时检查您的模板。

// 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 :(得分:0)

我没有得到你的确切问题,但我会改变这个:

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

答案 2 :(得分:0)

<h3>Hello {{ data.username }}</h3>

<p>Change yours personal data</p>

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

答案 3 :(得分:0)

我找到了解决方案。将来,如果有人在寻找

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