我使用Angular5和httpClient来请求一个rest api.我的问题是我完全得到了对象列表但我无法获得单个对象.我使用这个模块的模块我有一个服务,我打电话到api-rest:
getUser(id: string) {
return this.http.get<IUserComponent>('apiAddress/getbyid?id=' + id);
}
Run Code Online (Sandbox Code Playgroud)
在组件中我称之为
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
this.getUser(this.id);
}
getUser(id): void {
this.userService.getUser(id).subscribe(data => {
this.user = data;
});
}
Run Code Online (Sandbox Code Playgroud)
我在我的模板中调用用户:
<p>
{{user.name}}
</p>
Run Code Online (Sandbox Code Playgroud)
当我这样做时,我得不到任何显示和错误
TypeError: _co.user is undefined
ERROR CONTEXT Object { view: Object, nodeIndex: 12, nodeDef: Object, elDef: Object, elView: Object }
Run Code Online (Sandbox Code Playgroud)
我可以显示一些内容,但如果在服务中我说我想要一个数组,我仍然会收到错误
getUser(id: string) {
return this.http.get<IUserComponent[]>('apiAddress/getbyid?id=' + id);
}
Run Code Online (Sandbox Code Playgroud)
当我打电话给我时,我说
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
this.getUser(this.id);
}
getUser(id): void {
this.userService.getUser(id).subscribe(data => {
this.user = data[0];
}); …Run Code Online (Sandbox Code Playgroud) 我是角度4的新手,我正在尝试构建我的第一个应用程序.
标题显示在屏幕上,但在控制台中出现此错误 :
这是html文件中的第26行:
<h1>{{result.title}}</h1>
Run Code Online (Sandbox Code Playgroud)
这是TravelDetailComponent:
export class TravelDetailComponent implements OnInit {
result: string[];
id: number;
constructor(private http: Http, private globals: Globals, private activatedRoute: ActivatedRoute) {
}
ngOnInit() {
this.activatedRoute.params.subscribe((params: Params) => {
this.id = params['id'];
console.log(this.id);
});
this.http.get(this.globals.baseUrl + 'travels/' + this.id)
.map(res => res.json()).subscribe(result => this.result =
result);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么标题显示在屏幕上,但我在控制台中出现此错误,我该如何解决?
我有一个BookDetailComponent映射为url 的组件/books/:id.在angular 2路由器中是否有任何方法可以确保只有在从服务器检索到Bookgiven 后才能打开此组件id?
我正在寻找像Angular 2路由器中的ui-router resolve类似的功能.
/*** BookComponent ***/
@RouteConfig([
{path: "/books/:id", component: BookDetailComponent, as: "BookDetail"},
])
export class BookComponent {
}
/*** BookDetailComponent ***/
export class BookDetailComponent {
book:Book;
constructor(private bookService:BookService,
private routeParams:RouteParams) {
}
ngOnInit() {
let id = this.routeParams.get("id");
this.bookService.getBook(parseInt(id))
.subscribe(book => this.book = book.json());
}
}
Run Code Online (Sandbox Code Playgroud)