Angular 4 - 即使在Promises中的“.then”内,组件变量仍未定义

时间:2017-12-12 15:19:56

标签: angular angular2-services

非常奇怪,即使在Promise的.then方法中分配了值,变量仍未定义。

  this.parentService.getParent(this.fatherId)
  .then(parents => { 
                      if(parents != null && parents.id)
                      {
                          **this.parents = parents ;**
                        console.log(JSON.stringify(parents));
                          this.motherId = parents.mother.idCardNumber;
                          this.child.fatherId = this.fatherId;
                          this.child.motherId = parents.mother.idCardNumber;
                      }else
                        {
                          this.initParents();
                        }
                    });

}

我确实希望变量this.parent在service getParent返回父承诺时具有相同的父值。

现在,html模板正在异步填充,但组件变量,this.parent仍未定义,我真的不明白为什么。   console.log(JSON.stringify(parents))打印一个空的JSON数组:

  

{ “地址”:{}, “接触”:{}, “父亲”:{ “地址”:{}, “接触”:{}}, “母亲”:{ “地址”:{}, “接触”:{}}}

parent.service.ts:

getParent(id:string):承诺   {

this.parent = new Parent(new Person(), new Person());

console.log("Current Parent: " + this.parent.id);
  //this.parent.id = "1";
    this.db.list<Parent>('/Parents').snapshotChanges().subscribe(
           parents => {
              //console.log(childs);

              for(let i = 0 ; i < parents.length ; i ++)
              {

                console.log(parents[i].payload.val());

                //let mparent = parents[i].payload.val();

                  this.assignParent(parents[i].payload.val(), id);                      

              }
            });

    return Promise.resolve(this.parent);

}

    assignParent(parent: Parent, id : string): void
{

    if(parent != null)
        {
          console.log("The ParentId:  " + id + "  Local: " + parent.id );

            if(parent.id == id)
            {
                //let mparent = parent;
                //this.copyChild(child);
                //this.parent = Object.assign({}, parent);

                //console.log("JSON:  " + JSON.stringify(this.child));
                this.parent.id = parent.id;

                this.helper.copyPerson(this.parent.father, parent.father);
                this.helper.copyPerson(this.parent.mother, parent.mother);


                //this.parent = parent;
                console.log("YES:  " + this.parent.id);


            }

        }


}

0 个答案:

没有答案