Fetch data once with Observables in Angular 2

前端 未结 4 1979
旧时难觅i
旧时难觅i 2020-12-29 12:32

I have a service, what is used several times from a lot of my Angular 2 components. It fetches customer data from a Web API and returns an Observable:

getCus         


        
4条回答
  •  清歌不尽
    2020-12-29 12:55

    the share operator give the possibility to use the same stream's result with multiple observers. It could be good but you generate a new observable stream each time you call getCustomers(), there is no point to call share() since you didn't subscribe multiple times to this stream.

    If you wanna share the data with multiple observers but make only one http call you simply have to create a second stream, feed by the http one, containing the data. After that, all your components could subscribe to it.

    The code could be something like that

    @Injectable()
    class FooBar {
    
        public dataStream:Subject = new Subject();
    
        constructor(private http:Http) {}
    
        public getCustomers() {
            return this.http
            .get(this.baseURI + this.url)
            .map((response:Response) => response.json())
            .map((data) => {
                this.dataStream.next(data); 
                return data;
            })
        }
    
    }
    
    
    @Component({})
    class BarFooHttpCaller {
        constructor(private foobar:Foobar) {}
    
        ngOnInit() {
            this.foobar.getCustomers().subscribe(() => { console.log('http done') });
            this.foobar.dataStream.subscribe((data) => {
                console.log('new data', data);
            })
        }
    }
    
    @Component({})
    class OtherBarFoo {
        constructor(private foobar:Foobar) {}
    
        ngOnInit() {
            this.foobar.dataStream.subscribe((data) => {
                console.log('new data', data);
            })
        }
    }
    

提交回复
热议问题