Rxjs angular2 subject不调用subscribe函数

时间:2017-07-23 18:30:46

标签: angular rxjs jwt angular2-services

我是rxjs的初学者,目前在调用subscribe函数时遇到问题。我的代码是这样的:

组件A:

getAllData() {
    this.dataService.getDataA().subscribe(
    data => console.log(data))
}

的DataService:

getDataA() {
    let url = "/services/data";
    return this.getData(url)
}

getData() {
//first without JWT
    let sub = new Subject<Response>();
    this.http.get(param1)
        .subscribe(
            res => sub.next(res)
            err => {
                //401 without JWT so I call authService
                this.authServ.getDataWithToken().subscribe(
                    data => sub.next(data)
                )} 
    return sub.asObservable()
}



getData2() {
    //first without JWT
    let sub = new Subject<Response>();
    this.http.get(param1)
        .subscribe(
            res => sub.next(res)
            err => {
                //401 without JWT so I call authService
                this.authServ.getDataWithToken().subscribe(
                    data => sub.next(data)
                )} 
    return sub.asObservable()
}

authService:

getDataWithToken() {
    let sub = new Subject<Response>()
    this.getToken().subscribe(
        token=> {
        //reachable just once
            this.http.get(url, new RequestOption(tokenHeader))
            .subscribe(
              data => sub.next(data)
            )
    return sub.asObservable();
}


getToken(url) {
    let sub = new Subject<string>();

    if (this.tokens[url])
        // token is already in memory - console log proves it's reachable
        sub.next(this.tokens[url])
    else {
        // also reachable
        this.http.get(newToken).subscribe(
            (data) => sub.next(data))

    return sub.asObservable()
}

问题是,当我尝试使用令牌 - &gt;到达两个转义点时转到auth服务,只是第一个工作没有问题,第二个被困在authService.getDataWithToken.subscribe中,它似乎在等待数据,但什么都没有。我找到了一个解决方法(真的很脏),如果我在服务中复制函数getData,并从一个组件调用getData和其他一个getData2,它就可以了。

我知道,有更多的订阅,这可能是问题所在。但有人能解释我为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

您是否可以尝试使用此代码替换您的getToken,我想您在订阅之前已经发送了包含主题的令牌

getToken(url) {
    let sub = new Subject<string>();
    if (this.tokens[url])
    // token is already in memory - console log proves it's reachable 
    {
        return Observable.of(this.tokens[url])
    } else { // also reachable 
        this.http.get(newToken).subscribe((data) => sub.next(data))
        return sub.asObservable()
    }
}