如何从方法返回的对象访问属性

如何从方法返回的对象访问属性

问题描述:

我无法通过getClient方法设置值"contact.company_name".

I'm unable to set the value "contact.company_name" from the method getClient.

  getContacts() {
    this.contactService.getContacts().subscribe(
      data => {
        for (let contact of data) {
          contact.company_name = this.getClient(contact);
          console.log(contact);
        }
        this.contacts = data
      },
      error => console.log(error),
      () => this.isLoading = false
    );
  }

响应是this.getClient(contact)http-request是:

The response is of this.getClient(contact) http-request is:

{_id: "59f43f1a3a2fc421c00ad8b1", name: "company2", street: "street 2", zipcode: "45678",…}

如何使contact.company_name像company.name一样? contact.company中的ID与company._id中的ID相同. http的请求和响应是正确的.

How I can make contact.company_name is like company.name? The id in contact.company is the same id like in company._id. The http-request and response is right.

例如,联系人是:

{
anrede : "sir"
company : "59f43f1a3a2fc421c00ad8b1"
nachname :"surname1"
titel : "dr."
vorname : "name1"
__v : 0
_id : "59f43f363a2fc421c00ad8b2"   
}

如果您知道公司将永远存在,只需在行末添加.name:

If you know that the company will always exist, simply add .name to the end of the line:

contact.company_name = this.getClient(contact).name;

如果它可能不存在,则需要先检查一下:

If it might not exist, you need to check that first:

const company = this.getClient(contact);

if (company) {
    contact.company_name = company.name;
}

编辑

现在,我了解您的getClient方法如何工作,您说它的响应是JS对象,但是它不返回任何内容,而是订阅了一个可观察的对象.

Now I see how your getClient method works, you said that its response is JS object, but it does not return anything and instead subscribing to an observable.

这是一种使用forkJoin解决此问题的方法(您可能需要导入该运算符才能使用它):

Here is a way how to solve this using forkJoin (you will probably need to import that operator to use it):

getContacts() {
  return this.contactService.getContacts()
    .flatMap(data => {
      if (data.length > 0) {
        return Observable.forkJoin(
          data.map(contact => {
            return this.contactService.getClient(contact)
              .map(company => {
                contact.company_name = company.name;
                console.log(contact);

                return contact;
              });
          }));
      }

      return Observable.of([]);
    });
}

有关如何组合可观察物的更多示例,请参见本文:

For more examples of how to combine observables, see this article:

http://blog.danieleghidoli.it/2016/10/22/http-rxjs-observables-angular/