forkJoin没有首先在Api方法

时间:2017-07-13 16:32:50

标签: angular typescript observable fork-join

我写了forkJoin,如下所示。如果我没有将api方法设置为first,它就无法工作(也没有错误)。你能告诉我为什么吗?

my.ts

    let getMyBookMarksApi = this.userService.getMyBookMarks(this.page);//needs first()
    let getMyTopicsApi = this.userService.myTopic();//needs first()

    Observable.forkJoin([getMyBookMarksApi, getMyTopicsApi])
        .subscribe(res => {
            this.setMyProfile(res[0]);
            this.arrangeMyTopics(res[1]);
        },
        error => { },
        () => { });

service.ts

 myTopic() {
 return this.api.get(config.myTopics).map((res: any) => res.json()).first();//without first forkjoin is not working.Why?
 }

api.ts

 get(api) {
        return new Observable(observer => {
            let header = new Headers();
            this.createHeader(header)
                .then(() => {
                    let options = new BaseRequestOptions();
                    options.withCredentials = true;
                    options.headers = header;
                    this.http.get(api, options)
                        .subscribe(response => {
                            observer.next(response);
                        }, (e) => {
                            observer.error(e);
                        });
                })
        })
    }

Api响应就像这样:

{
  "num_of_definitions": 11,
  "categories": [
    {
      "id": 68,
      "name": "Founders",
      "num_of_definitions": 1,
      "icon": {
        "large": ""
      },
      "from_color": "#1E3C72",
      "to_color": "#2A5298"
    },
    {
      "id": 27,
      "name": "Innovation",
      "num_of_definitions": 1,
      "icon": {
        "large": ""
      },
      "from_color": "#EE0979",
      "to_color": "#FF6A00"
    },
    {
      "id": 58,
      "name": "Life success",
      "num_of_definitions": 1,
      "icon": {
        "large": ""
      },
      "from_color": "#D53369",
      "to_color": "#CBAD6D"
    },

  ]
}

1 个答案:

答案 0 :(得分:1)

Forkjoin通过并行订阅所有observable来工作,并且只有当所有这些observable都已完成时才会加入它们。这里的关键字是完成时。 运算符.first()从一个observable中获取第一个发出的元素,然后完成。可能是因为你的源观察源没有完成

完成示例以完成在onNext

之后添加onComplete行
 get(api) {
    return new Observable(observer => {
        let header = new Headers();
        this.createHeader(header)
            .then(() => {
                let options = new BaseRequestOptions();
                options.withCredentials = true;
                options.headers = header;
                this.http.get(api, options)
                    .subscribe(response => {
                        observer.next(response);
                        // add this line, it should trigger the completion of the outer observable
                        observer.complete();
                    }, (e) => {
                        observer.error(e);
                    });
            })
    })
}