Angular5 ParamMap 和 HttpClient
Angular5 ParamMap and HttpClient
如何通过 Angular5 中的服务让 ParamMap 与 HttpClient 一起工作?
组件
// importing the service, ActivatedRoute, ParamMap, switchMap, etc
public value;
constructor(private myService: MyService, private activatedRouter: ActivatedRoute) { }
ngOnInit() {
this.value = this.activatedRouter.paramMap
.switchMap((params: ParamMap) => this.myService.getOne(params.get('id')));
}
服务
import { HttpClient } from '@angular/common/http';
// ...
constructor(private httpClient: HttpClient) { }
getOne(id) {
return this.httpClient.get(`http://my.api/${id}`);
}
目前,如果我在我的组件中执行 console.log(this.value)
,我会得到一个 AnonymousSubject
。
问题是,如何使用 ParamMap 并从 HttpClient 获取值?我知道我可以使用路由器快照 - 我已经做到了并且它有效,但我想让这个例子也能正常工作。
您需要 subscribe() 来获取数据。它在您获取数据的订阅中
ngOnInit() {
this.activatedRouter.paramMap
.switchMap((params: ParamMap) =>
this.myService.getOne(params.get('id'))).subscribe((data:any)=>{
this.value=data
});
}
根据 CozyAzure 的评论,最终解决方案是
this.activatedRouter.paramMap
.switchMap((params: ParamMap) =>
this.myService.getOne(params.get('id')))
.subscribe(data => value = data);
}
如何通过 Angular5 中的服务让 ParamMap 与 HttpClient 一起工作?
组件
// importing the service, ActivatedRoute, ParamMap, switchMap, etc
public value;
constructor(private myService: MyService, private activatedRouter: ActivatedRoute) { }
ngOnInit() {
this.value = this.activatedRouter.paramMap
.switchMap((params: ParamMap) => this.myService.getOne(params.get('id')));
}
服务
import { HttpClient } from '@angular/common/http';
// ...
constructor(private httpClient: HttpClient) { }
getOne(id) {
return this.httpClient.get(`http://my.api/${id}`);
}
目前,如果我在我的组件中执行 console.log(this.value)
,我会得到一个 AnonymousSubject
。
问题是,如何使用 ParamMap 并从 HttpClient 获取值?我知道我可以使用路由器快照 - 我已经做到了并且它有效,但我想让这个例子也能正常工作。
您需要 subscribe() 来获取数据。它在您获取数据的订阅中
ngOnInit() {
this.activatedRouter.paramMap
.switchMap((params: ParamMap) =>
this.myService.getOne(params.get('id'))).subscribe((data:any)=>{
this.value=data
});
}
根据 CozyAzure 的评论,最终解决方案是
this.activatedRouter.paramMap
.switchMap((params: ParamMap) =>
this.myService.getOne(params.get('id')))
.subscribe(data => value = data);
}