【发布时间】:2016-09-10 16:04:55
【问题描述】:
我有一个组件应该从服务中检索数据。
这是我的组件:
@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...
有人可以帮忙吗?
附:我很困惑,因为我的用例(有一个组件调用使用 http 的服务方法)与此处提供的角度示例非常相似:http://plnkr.co/edit/DRoadzrAketh3g0dskpO?p=preview
【问题讨论】:
-
这很难说,但您似乎在实例化后的任何时候都没有调用
updateFirstName。此外,它需要异步处理。与您对ngOnInit所做的相同。如果不是这样,我知道。 -
+
updateFirstName在你的服务中没有返回任何东西。 -
updateFirstName在这里无关紧要。相关的是userAccountService.getCurrentUserAccount。 -
我可能一开始就不应该在此处包含 updateFirstName。
标签: angular angular2-services rxjs5