我是Angular的新手,有问题。我试图在组件之间传递一些数据。我已经尝试过在互联网上找到的其他解决方案,但我做得不好。
我通过一个组件中的api通过服务获取具有两个值(标题和id)的数据(效果很好)。在单击标题时,我想重定向到另一个组件并接收单击的标题的ID,以便调用另一个api端点。如何调用特定值ID并将其带入其他组件?
这是我的第一个服务(工作中):
export class HeadlinesService {
apiUrl = '...'
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
constructor(private _http: HttpClient) { }
getHeadlines(): Observable<Headline[]> {
return this._http.get<Headline[]>(this.apiUrl);
}
}
我的标题班:
export class Headline {
heading: string;
id: string;
source: string;
}
在这里我打电话给服务部门以显示标题(工作中)
export class NewArticleComponent implements OnInit {
headlines$: Headline[];
constructor(private headlineService: HeadlinesService, private deleteService: DeleteService, private router: Router) { }
ngOnInit() {
return this.headlineService.getHeadlines()
.subscribe(headline => this.headlines$ = headline)
}
}
我需要一个服务,该服务从上面的服务接收ID(但仅是ID),并使用它调用另一个api端点。
apiURL = '.../{id}'
从其中调用数据应该像上面的工作服务一样工作,所以我唯一的问题是将ID从一个服务传递到另一个服务。
我希望有人可以帮助我:)
答案 0 :(得分:0)
您可以通过以下方式传递导航数据:
constructor(...
router: Router,
...) {}
goToPage(headerId) {
this.router.navigate(['/header'], { queryParams: { headerId } });
}
假设您正在以编程方式(从component.ts代码内部)进行此操作
在“接收”标头组件上
sub: Subscription;
headerId;
constructor(
private route: ActivatedRoute,
private router: Router) {}
ngOnInit() {
this.sub = this.route
.queryParams
.pipe(flatMap(params => {
this.headerId = params['headerId'];
return this.apiService.getById(this.headerId);
})).subscribe(
response => {
//You should have your header response from API here
}
);
}