[英]Calling angular Observable.subscribe() from common file
I am calling the below function from two file( ie x.ts and y.ts) but on checking from third party tool it showing me duplicate code in both file. 我从两个文件(即x.ts和y.ts)中调用以下函数,但是从第三方工具检查时,它显示了我在两个文件中都有重复的代码。 It is below message service which i am calling in both file.
我在两个文件中都在消息服务下面。
this.dataSubscription = this.dataService.allmesgeObeject.subscribe(data=> {
if (data) {
this.x= data.x;
this.y= data.y;
}
});
Can there be any way of putting subscribe function to a common file and received data it in their respective file. 可以采用任何方式将订阅功能置于通用文件中并将其接收到的数据存储在各自的文件中。
You can create Subject in your service and then subscribe to it from your two components. 您可以在服务中创建主题,然后从两个组件中进行订阅。 That way you will call the API only once and both components will be updated with the latest data
这样,您只需调用一次API,两个组件都将使用最新数据进行更新
export class DataService{
public allMessages: Subject<any> = new Subject();
constructor(
private http: HttpClient
) { }
allmesgeObeject() {
return this.http.get(...).pipe(
map((result) => {
this.allMessages.next(result);
}));
}
}
Then call it once from outside the service 然后从服务外部调用一次
this.dataService.allmesgeObeject.subscribe();
And now in two of your components you can subscribe to that subject you previously created. 现在,在您的两个组件中,您可以订阅先前创建的主题。
this.dataService.allMessages.subscribe(data=> {
if (data) {
this.x= data.x;
this.y= data.y;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.