簡體   English   中英

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獲取值? 我知道我可以使用路由器快照-我已經完成了並且可以使用,但是我也希望這個例子也可以使用。

您需要subscription()來獲取數據。 在訂閱中,您可以獲取數據

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);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM