我对可观测量的知识是有限的,所以我可能会明显地知道我在这里做错了什么。
在我的Angular 2组件上的Init上,此调用发生。
ngOnInit(): void {
this.route.paramMap
.switchMap((params: ParamMap) => this.userService.getUser(+params.get('id')))
.subscribe(user => this.user = user);
console.info(this.user.id);
}
这称为此服务方法:
getUser(id: number): Promise<User> {
let url = this.baseUserUrl + 'GetUserAsync?id=' + id;
return this.http.get(url)
.toPromise()
.then(resp => resp.json() as User);
};
使用用户对象的html代码片段
<div class="row padding-left">
<div class="col-sm-6 base-info-container info-box-details">
<table class="info-box">
<tr>
<td>User Id: {{ user.id }}</td>
<td>Email: {{ user.email }}</td>
</tr>
</table>
</div>
</div>
Resp.json肯定会带回数据,但是组件上的用户变量没有设置,我不明白为什么。
答案 0 :(得分:1)
您可能必须使用安全导航操作符(Angular docs) ?
:user?.id
;当您的视图呈现时,您的数据尚未被提取。
同样在您的使用案例中,我在激活之前使用Resolver
来获取数据
您的组件,请参阅:
// in your route module
const userRoutes: Routes = [
{
path: 'user/:id',
component: YourComponent,
resolve: {
user: UserResolverService
}
];
// User Resolver Service
import { Injectable } from '@angular/core';
import {ActivatedRouteSnapshot, Resolve} from '@angular/router';
import {UserService} from 'your.user.service';
@Injectable()
export class UserResolverService implements Resolve<any> {
constructor(private userService: UserService) { }
resolve(route: ActivatedRouteSnapshot) {
return
this.userService.getUser(route.paramMap.get('id'));
}
}
// In your user component
constructor (private route: ActivatedRoute) { }
ngOnInit() {
// Your snapshot's data matching user you defined in your route resolve
this.user = this.route.snapshot.data['user'];
}
这篇伟大的文章由Whiletram解释得很好:resolving-route-data-in-angular-2