可观察量代码永远不会被执行



我不知道为什么代码没有运行。甚至控制台.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}

我跟着这个

为了使http模块进行其余调用,您必须向其添加subscribe

在您的情况下,这将是:

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

最新更新