![](/img/trans.png)
[英]Angular/rxjs/Subject/BehaviorSubject share http service data across multiple components
[英]Angular 6 http + Observable + Subject across multiple components
我正在嘗試共享服務提供商通過HTTP GET檢索的數據。 我在http.service
獲取數據:
@Injectable()
export class HttpService {
constructor(private http: HttpClient) { }
public getData4(url: string): Observable<Premium[]> {
return this.http.get<Premium[]>(url);
}
}
應用的路由為:
<TabsComponent>
<TablesComponent>
<TablesComponent/>
</TabsComponent>
在tabs.component.ts中,我有:
export class TabsComponent implements OnInit {
myUrl4All = 'http://localhost:8083/RCCT-2.0-SNAPSHOT/rest/v2';
premiumsO: Premium[] = [];
constructor(private httpService: HttpService, private entity1Service: Entity1Service) { }
ngOnInit() {
this.httpService.getData4(this.myUrl4All).subscribe(data => this.premiumsO =
data['premiumList']);
}
}
在我的tabs.component.html中,我有:
<div>
<app-tables-component></app-tables-component>
</div>
和我的tables.component.ts:
export class TablesComponent implements OnInit {
constructor() { }
returnedArray: Premium[] = [];
ngOnInit(): void {
this.returnedArray = ?????????
}
}
我的問題是:現在我有了一個可觀察的http.service
,但是我想通過使用tables.component
來捕獲並顯示來自tables.component
http的數據。 我應該如何更改代碼來做到這一點?
一種簡單而快速的方法是讓您在子組件上使用@Input
(記住從@angular/core
導入),如下所示:
export class TablesComponent implements OnInit {
constructor() { }
@Input()
returnedArray: Premium[] = [];
ngOnInit(): void { }
}
然后在您的父template.html
傳遞父數據,如下所示:
<div>
<app-tables-component [returnedArray]="premiumsO"></app-tables-component>
</div>
編輯:根據下面的評論
將Array
添加到服務中,使其可觀察並訂閱。 喜歡:
@Injectable()
export class HttpService {
premiumsO: BehaviorSubject<Premium[]> = new BehaviorSubject<Premium[]>();
constructor(private http: HttpClient) { }
public getData4(url: string): void {
this.http.get<Premium[]>(url).subscribe(data => {
this.premiumsO.next(data['premiumList']);
});
}
}
然后在您的父控制器和子控制器中,訂閱premiumsO
例如:
export class TablesComponent implements OnInit {
constructor(private httpService: HttpService) { }
private subscription: Subscription;
returnedArray: Premium[] = [];
ngOnInit(): void {
this.subscription = this.httpService.premiumsO.subscribe(data => this.returnedArray = data);
}
ngOnDestroy() {
this.subscription.unsubscribe().
}
}
在父母中做同樣的事情。 不知道這是否是正確的解決方案,但我會這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.