简体   繁体   English

Angular-类似于http.get的可观察到的但没有请求

[英]Angular - Observable similar to http.get but without request

I have this observable http request 我有这个可观察到的http请求

refreshToken() {
    return this.http.get(this.siteService.apiDomain() + '/api/token?token=' + localStorage.getItem('JWToken'), {})
        .map((response: Response) => {
            return response;
        })
}

and I'm calling the observable like this 我这样称呼可观察者

return this.refreshTokenService.refreshToken()
                .flatMap((result: any) => {
                    // if got new access token - retry request
                    if (JSON.parse(result._body).token) {
                        localStorage.setItem('JWToken', JSON.parse(result._body).token);
                    }
                    this.setHeaders(url);
                    return this.request(url, options);
                })

And my problem is that if I have multiple parallel requests I'm making multiple times the refreshToken(). 我的问题是,如果我有多个并行请求,那么我将多次进行refreshToken()。 I want to find a way to make a fake http call, and return the token that I already know or nothing. 我想找到一种方法来进行虚假的http调用,并返回我已经知道的令牌或什么都不返回。

Observable.empty() // Failed to compile (Type '{}' is not assignable to type 'Response'.)
Observable.empty().filter(() => {return true}) // Compiles but it stop the flatMap sequence.

I'm not sure I completely understand, but maybe you want Observable.of() ? 我不确定我是否完全理解,但也许您想要Observable.of()吗?

Here is an example of where I've used it. 这是我使用过的地方的一个例子。 If the Id is 0, it returns an initialized product as an Observable. 如果Id为0,则返回已初始化的产品作为Observable。

import 'rxjs/add/observable/of';
...

getProduct(id: number): Observable<IProduct> {
    if (id === 0) {
        return Observable.of(this.initializeProduct());
    };
    const url = `${this.baseUrl}/${id}`;
    return this.http.get(url)
        .map(this.extractData)
        .do(data => console.log('getProduct: ' + JSON.stringify(data)))
        .catch(this.handleError);
}

I would recommend use of BehaviourSubjects, Its will allow you to store the last value until either the component destroyed or you face it to change. 我建议使用BehaviourSubjects,它可以让您存储最后一个值,直到组件被破坏或面临更改为止。 Also when the value changes on the BehaviourSubject; 同样,当BehaviourSubject上的值更改时; every component that have subscribe to it also recieves new data. 订阅它的每个组件也会接收新数据。 Plus as a added bonus you dont need to call the server evrytime a component want to get the value like Observable, since its storing the value, you can get the value anytime without calling the server. 另外,作为额外的好处,您不需要调用服务器evrytime即可获取类似于Observable之类的值,因为该组件存储了值,因此您可以随时获取该值而无需调用服务器。 BehaviourSebject example 行为目标示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM