使用角度 4 订阅的行为主体



我正在使用带有可观察的角度4。

我需要将数据一个组件共享到另一个组件,因为我正在使用可观察的行为主体。

这是我的代码

import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Http, Response } from '@angular/http';
public _searchResultOne = new Subject<any>();
searchResultOne$ = this._searchResultOne.asObservable();

constructor(private http: Http) {}
newsearch() {
return Observable.forkJoin(
this.http.get(API),
this.http.get(API)
)
.subscribe(latestValues => {
const [data_changes, data_all] = latestValues;
this._searchResultOne.next(latestValues);
})
}
getNewSearchResults(): Observable < any > {
return this.searchResultOne$;
}

实际上,我显示了加载更多的数据。使用此函数获取结果 getNewSearchResults((。

这是我的组件。

import { SearchService } from '../../shared/services/search.service';
import { ISubscription } from 'rxjs/Subscription';
results;
constructor(
public searchService: SearchService) {
}
ngOnInit() {
this.searchOne();
}
searchOne() {
this.subscription = this.searchService
.getNewSearchResults()
.subscribe(res => {
console.log("result", res);
var freelisting = res[1].response.docs;
this.results = this.results.concat(this.freelisitingArray);
}
}

我只是安慰了回应。 它被多次调用。为什么?

结果被多次订阅,所以我得到重复的结果。如何避免多次订阅。

我也试图用this.subscription.unsubscribe()破坏.但我仍然得到了更多重复的结果。

我该如何解决此问题。

请告诉我,

谢谢。

似乎您正在尝试使用单一实例服务在两个(或多个(组件之间共享它。如果是这种情况,请查看provider: [SearchService]部分中的模块代码,您必须从组件中删除此提供程序,并在app.module.ts.中添加一个提供程序这样,您将只有一个服务实例,并在两个组件中保留相同的值。

最新更新