Observables代码永远不会执行

时间:2017-10-30 17:06:41

标签: angular typescript

我不知道为什么代码没有运行。 即使是console.log(' 1')也不会出现。

  ngOnInit() {
    this.getContacts();
    this.getClients();
  }

  getContacts(): Observable<any[]> {
    return this.http.get('/api/contacts')
      .map((res: any) => res.json()).flatMap((contacts: any[]) => {
        if (contacts.length > 0) {
          console.log(1);
          const observables = Observable.forkJoin(
            contacts.map((contact: any) => {
              return this.http.get('/api/client/' + contact.company_name)
                .map((res: any) => {
                  let company_name: any = res.json();
                  contact.company_name = name;
                  console.log(contact.company_name);
                  return contact;
                });
            })
          );
          console.log(observables);
          return observables;
        }
        return Observable.of([]);
      }
    );
  }

localhost:4200 / api / contacts的简单回复是:

[{"_id":"59f43f363a2fc421c00ad8b2","anrede":"sir","titel":"dr.","vorname":"name1","nachname":"surname1","company":"59f43f0e3a2fc421c00ad8b0","__v":0},{"_id":"59f43f443a2fc421c00ad8b3","anrede":"mrs","titel":"prof.","vorname":"name2","nachname":"surname2","company":"59f43f1a3a2fc421c00ad8b1","__v":0}]

localhost:4200 / api / client的简单响应是:

{"_id":"59f43f1a3a2fc421c00ad8b1","name":"company2","street":"street 2","zipcode":"45678","city":"city2","__v":0}

我关注this

1 个答案:

答案 0 :(得分:2)

要让http模块拨打其余电话,您必须向其添加subscribe

在你的情况下,这将是:

this.getContacts().subscribe((data) => {//do something with data})