我有一個組件,應該從服務中檢索數據。問題與角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
很難說,但看起來你沒有在實例化後隨時調用'updateFirstName'。另外,它需要異步處理。就像你使用'ngOnInit'一樣。如果這不是,讓我知道。 – ZenStein
+您的服務中的'updateFirstName'不返回任何內容。 – ZenStein
'updateFirstName'在這裏是不相關的。它與'userAccountService.getCurrentUserAccount'是相關的。 – balteo