问题与角2组件不订阅服务在适当的时间观察
问题描述:
我有一个组件,应该从服务中检索数据。问题与角2组件不订阅服务在适当的时间观察
这里是我的组件:
@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
答
角ngOnInit()
之前就已经解决了绑定。你,你只是调用异步调用服务器获取数据,这将最终到达(并执行你传递给this.userAccountService.getCurrentUserAccount().subscribe(...)
回调为了避免一个错误,当currentUserAccount
仍然null
当角结合你可以使用视图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"/>
很难说,但看起来你没有在实例化后随时调用'updateFirstName'。另外,它需要异步处理。就像你使用'ngOnInit'一样。如果这不是,让我知道。 – ZenStein
+您的服务中的'updateFirstName'不返回任何内容。 – ZenStein
'updateFirstName'在这里是不相关的。它与'userAccountService.getCurrentUserAccount'是相关的。 – balteo