角度2组件未及时订阅服务中可观察的问题

时间:2016-05-14 13:29:33

标签: angular angular2-services rxjs5

我有一个应该从服务中检索数据的组件。

这是我的组件:

@Component({
    templateUrl: 'app/dashboard/useraccount/firstname/useraccount-firstname.component.html',
    directives: [ROUTER_DIRECTIVES],
    pipes: [TranslatePipe]
})
export class UserAccountFirstNameComponent implements OnInit {

    currentUserAccount:Object;
    errorMessage:string;

    constructor(private userAccountService:UserAccountService) {
    }

    ngOnInit() {
        this.userAccountService.getCurrentUserAccount()
            .subscribe(
                param=> this.currentUserAccount = param,
                error => this.errorMessage = <any>error
            );
    }

    updateFirstName() {
        this.userAccountService.updateFirstName(this.currentUserAccount);
    }

}

以下是相应的服务:

@Injectable()
export class UserAccountService {

    constructor(private http:Http) {
    }

    getCurrentUserAccount():Observable<Object> {
        return this.http.get('/api/useraccount')
            .map(this.mapUserAccount)
            .catch(this.handleError);
    }

    updateFirstName(currentUserAccount) {
        this.http.patch('/api/useraccount/firstname/' + currentUserAccount.firstName, null);
    }

    private mapUserAccount(res:Response) {
        console.log(res.json());
        return res.json();
    }

    private handleError(error:any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg = error.message || 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }

以下是UserAccountService的提供商:

bootstrap(MainComponent, [ROUTER_PROVIDERS,
    HTTP_PROVIDERS,
    TRANSLATE_PROVIDERS,
    SessionService,
    UserAccountService,
    TranslateService,
    provide(RequestOptions, {useClass: ApplicationRequestOptions}),
    provide(LocationStrategy, { useClass: HashLocationStrategy }),
    provide(TranslateLoader, {
        useFactory: (http:Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),
        deps: [Http]
    })]);

以下是模板的相关部分:

<input type="text"
       ngControl="firstName"
       #firstName="ngForm"
       required
       minlength="2"
       maxlength="35"
       pattern_="FIRST_NAME_PATTERN"
       [(ngModel)]="currentUserAccount.firstName"
       placeholder="{{'FIRST_NAME_FORM.NEW_FIRST_NAME'| translate }}"
       class="form-control"/>

问题在于,在呈现模板时,currentUserAccount在ngModel中仍为undefined ...

有人可以帮忙吗?

P.S。我很困惑,因为我的用例(有一个组件调用使用http的服务方法)与这里提供的角度样本非常相似:http://plnkr.co/edit/DRoadzrAketh3g0dskpO?p=preview

1 个答案:

答案 0 :(得分:1)

Angular在ngOnInit()之前解析绑定。您只需调用对服务器的异步调用来获取最终到达的数据(并执行您传递给this.userAccountService.getCurrentUserAccount().subscribe(...)的回调

要避免在currentUserAccount仍为null时出现错误,当Angular绑定视图时,您可以使用Elvis或安全导航操作符?.进行父对象绑定{{1}但不支持事件到父绑定[]这不支持(有讨论要添加对此的支持)你可以使用这种更详细的风格:

()