代码之家  ›  专栏  ›  技术社区  ›  Mathew Berg Lucas

写一个你也可以订阅的观察表,并进行一次HTTP调用

  •  0
  • Mathew Berg Lucas  · 技术社区  · 8 年前

    在AnguylarJS中,我会在一个服务中做类似的事情:

    function call(){
        if(service.promise){
            return service.promise
        };
        service.promise = http.get(...)
            .then(function(){
                ...
                return ...;
            }, function(){
                ...
            });
        return service.promise;
    }
    

    call(); //fires the http call
    call(); //does not fire the http call again
    

    我尝试用角度上的观察值来复制它,但是HTTP调用总是为每个订阅触发:

    call(): Observable<...>{
        if(service.observable){
            return service.observable;
        }
    
        service.observable = this.httpClient.get<...>(...)
            .flatMap(data => {
                ...
                return of(...);
            });
    
        return service.observable;
    }
    

    call() //fires the http call
        .subscribe((data) => {
            console.log(data);
        })
    call() //fires the http call again
        .subscribe((data) => {
            console.log(data);
        })
    

    我也可以在这里做反模式。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Mathew Berg Lucas    8 年前

    call(): Observable<...>{
        if(service.observable){
            return service.observable;
        }
    
        service.observable = this.httpClient.get<...>(...)
            .pipe(
                map(data => {
                    ...
                    return ...;
                }),
                shareReplay(1)
            );
    
        return service.observable;
    }
    
    推荐文章