What is the correct way to share the result of an Angular Http network call in RxJs 5?

前端 未结 21 1376
广开言路
广开言路 2020-11-21 06:11

By using Http, we call a method that does a network call and returns an http observable:

getCustomer() {
    return          


        
21条回答
  •  面向向阳花
    2020-11-21 06:23

    Just use this cache layer, it does everything you requires, and even manage cache for ajax requests.

    http://www.ravinderpayal.com/blogs/12Jan2017-Ajax-Cache-Mangement-Angular2-Service.html

    It's this much easy to use

    @Component({
        selector: 'home',
        templateUrl: './html/home.component.html',
        styleUrls: ['./css/home.component.css'],
    })
    export class HomeComponent {
        constructor(AjaxService:AjaxService){
            AjaxService.postCache("/api/home/articles").subscribe(values=>{console.log(values);this.articles=values;});
        }
    
        articles={1:[{data:[{title:"first",sort_text:"description"},{title:"second",sort_text:"description"}],type:"Open Source Works"}]};
    }
    

    The layer(as an inject-able angular service) is

    import { Injectable }     from '@angular/core';
    import { Http, Response} from '@angular/http';
    import { Observable }     from 'rxjs/Observable';
    import './../rxjs/operator'
    @Injectable()
    export class AjaxService {
        public data:Object={};
        /*
        private dataObservable:Observable;
         */
        private dataObserver:Array=[];
        private loading:Object={};
        private links:Object={};
        counter:number=-1;
        constructor (private http: Http) {
        }
        private loadPostCache(link:string){
         if(!this.loading[link]){
                   this.loading[link]=true;
                   this.links[link].forEach(a=>this.dataObserver[a].next(false));
                   this.http.get(link)
                       .map(this.setValue)
                       .catch(this.handleError).subscribe(
                       values => {
                           this.data[link] = values;
                           delete this.loading[link];
                           this.links[link].forEach(a=>this.dataObserver[a].next(false));
                       },
                       error => {
                           delete this.loading[link];
                       }
                   );
               }
        }
    
        private setValue(res: Response) {
            return res.json() || { };
        }
    
        private handleError (error: Response | any) {
            // In a real world app, we might use a remote logging infrastructure
            let errMsg: string;
            if (error instanceof Response) {
                const body = error.json() || '';
                const err = body.error || JSON.stringify(body);
                errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
            } else {
                errMsg = error.message ? error.message : error.toString();
            }
            console.error(errMsg);
            return Observable.throw(errMsg);
        }
    
        postCache(link:string): Observable{
    
             return Observable.create(observer=> {
                 if(this.data.hasOwnProperty(link)){
                     observer.next(this.data[link]);
                 }
                 else{
                     let _observable=Observable.create(_observer=>{
                         this.counter=this.counter+1;
                         this.dataObserver[this.counter]=_observer;
                         this.links.hasOwnProperty(link)?this.links[link].push(this.counter):(this.links[link]=[this.counter]);
                         _observer.next(false);
                     });
                     this.loadPostCache(link);
                     _observable.subscribe(status=>{
                         if(status){
                             observer.next(this.data[link]);
                         }
                         }
                     );
                 }
                });
            }
    }
    
        

    提交回复
    热议问题