且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 API 数据从一个组件传递到另一个组件?

更新时间:2023-01-08 18:57:40

首先可以看到控制台登录组件是在从后端获取数据之前执行的.这个,因为这是异步,所以响应到达需要一段时间.

First of all, you can see that the console log in component is executed before fetching the data from the backend. This, because this is asynchronous, so it takes a while for the response to arrive.

第二个问题,与同一问题相关,即这是异步的,是您无法从订阅返回任何内容,您需要将 Observable 返回到您的组件并在组件订阅中,或者手动"执行或者然后使用异步管道.

Second problem, which is related to the same issue, i.e, this being asynchronous, is that you cannot return anything from subscribe, you need to return an Observable to your component and in the component subscribe, either doing it "manually" or then using the async pipe.

如果你想在最初获取另一个组件后将数据共享给其他组件,你可以做的是使用 BehaviorSubject,所以在你的服务中声明:

If you want to share data to other components after initially getting it another component, what you can do is to use a BehaviorSubject, so declare this in your service:

import {BehaviorSubject} from 'rxjs/BehaviorSubject';

//....

// don't use "any", type your data instead!
private apiData = new BehaviorSubject<any>(null);
public apiData$ = this.apiData.asObservable();

fetchData() {
  return this.http.get('/api/data').map((data) => {
    return data.json();
  })
}

// here we set/change value of the observable
setData(data) { 
  this.apiData.next(data)
}

在您正在获取数据并希望广播到其他组件的组件中,执行...

and in the component where you are fetching the data and want to broadcast to other components, do...

this.dataService.fetchData()
  .subscribe(data => {
    this.data = data;
    // set data in service which is to be shared
    this.dataService.setData(data)
  })

所以现在我们已经在这个初始组件中获取了数据,并设置了服务中的数据,这会广播给所有其他需要它的组件.在这些组件中,您只需订阅这个 observable.

So now we have in this initial component fetched the data, and setting the data in service, which is broadcast to all other components that need it. In those components you just subscribe to this observable.

constructor(private dataService: DataService) { 
  dataService.apiData$.subscribe(data => this.data = data)
}

此解决方案基于这样一种想法,即您拥有一个最初获取数据然后与其他组件共享数据的组件.

This solution is based on the idea that you have one component that initially gets the data and then shares it with other components.