angular 2 组件未及时订阅服务中的可观察对象的问题

Issue with angular 2 component not subscribing to observable in service in due time

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

这是我的组件:

@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"/>

问题是在呈现模板时,在 ngModel 中 currentUserAccount 仍然是 undefined...

有人可以帮忙吗?

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

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

的回调

为了避免在 currentUserAccount 仍然是 null 时出现错误 当 Angular 绑定视图时,您可以使用 Elvis 或安全导航运算符 ?. 进行父到-查看绑定 [] 但不支持事件到父绑定 () 这不受支持(有讨论添加对此的支持)你可以使用这种更详细的样式:

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