How to create behavior subject for object and subscribe to it on another component?

后端 未结 2 578

I have created a behaviour subject in a service class.

    public personObject: BehaviorSubject = new BehaviorSubject({
                        


        
2条回答
  •  别那么骄傲
    2020-12-31 21:57

    Service

    @Injectable()
    export class DataService {
    
      private _dataListSource: BehaviorSubject = new BehaviorSubject([]);
      dataList: Observable = this._dataListSource.asObservable().distinctUntilChanged();
    
      getDataList(): Observable {
          return this.httpService.get('/data').map(res => {
              this._dataListSource.next(res);
          });
      }
    }
    

    TS file

    export class DataComponent implements OnInit {
    
        public dataList$: Observable;
    
        constructor(public dataService: DataService) {}
    
        ngOnInit() {
            this.dataList$ = this.dataService.dataList;
            this.dataService.getDataList().subscribe();
        }
    }
    

    HTML file

    {{ data | json}}

提交回复
热议问题