Ждать данных от родителя - PullRequest
0 голосов
/ 12 марта 2020

Я знаю, что это частый вопрос, но решение, которое я видел в нескольких вопросах, не работает для меня.

У меня есть ребенок с @Input, который получает данные от родителя, но данные приходят из наблюдаемой, так что это asyn c.

Я читал, что *ngIf="data" может решить мою проблему, но что-то работает, и в других случаях я получаю undefined

parent. Html

<div *ngIf="submittedBy">
    <app-q-sub-subsequent-process [(confirm)]="confirm" [(submittedBy)]="submittedBy"
        [createProjectSubResponseFunction]="createProjectSubResponseFunction">
    </app-q-sub-subsequent-process>
</div>}

parent.ts

submittedBy: any = [{fisrtName:"", lastName:"", organization: ""}];
ngOnInit(){
    this.dataService.GetData().subscribe( response =>{
        this.submittedBy = response
    });
}

child.ts

@Input('submittedBy') submittedBy : any;
ngOnInit() {
    this.dataService.GetReviewerTypes().subscribe(response => {
        this.reviewerTypes = response;
        let user = {
            reviewerType: {
                reviewType:'', 
                reviewerTypeId: this.submittedBy.userTypeId
            }, 
            reviewer: {
                userId: this.submittedBy.id,
                user: `${this.submittedBy.lastName}, ${this.submittedBy.firstName}`
            }
        }
         /////////////This is where i get the error since user since 
         /////////////find returns undefiend because 
         /////////////user.reviewerType.reviewerTypeId = undefined
         user.reviewerType.reviewType = this.reviewerTypes.find(x => x.id = 
             user.reviewerType.reviewerTypeId).reviewType;
         let reviewerToAdd = { reviewerType: user.reviewerType, reviewer: user.reviewer }
         this.reviewersAdded = [{ ...reviewerToAdd }];
    },
         error => console.log(error)
    );
}

Ответ дочернего элемента - это массив, подобный следующему:

[
    {id:1, reviewType:'someType1'}
    {id:2, reviewType:'someType2'}
]

Иногда я получаю пользователя от моего ребенка, а иногда я получаю undefined и ошибку Cannot read property 'reviewType' of undefined

Я также пытался поймать изменения на ngOnChanges(), но он никогда не вводился там.

Я только что попробовал с сеттером:

child.ts

_submittedBy: any;
@Input('submittedBy') set submittedBy(value){
    this._submittedBy = value
};
ngOnInit() {
    this.dataService.GetReviewerTypes().subscribe(response => {
        this.reviewerTypes = response;
        let user = {
            reviewerType: {
                reviewType:'', 
                reviewerTypeId: this._submittedBy.userTypeId
            }, 
            reviewer: {
                userId: this._submittedBy.id,
                user: `${this._submittedBy.lastName}, ${this._submittedBy.firstName}`
            }
        }
         user.reviewerType.reviewType = this.reviewerTypes.find(x => x.id = 
             user.reviewerType.reviewerTypeId).reviewType;
         let reviewerToAdd = { reviewerType: user.reviewerType, reviewer: user.reviewer }
         this.reviewersAdded = [{ ...reviewerToAdd }];
    },
         error => console.log(error)
    );
}

1 Ответ

1 голос
/ 12 марта 2020

используйте asyn await в дочернем компоненте, надеюсь, это поможет

child.ts
    @Input('submittedBy') submittedBy : any;
    public data;
    async ngOnChanges() {
        if (this.submittedBy) {
          this.data = await this.submittedBy;
    }
    }

Html

   <div *ngIf="data">
        <app-q-sub-subsequent-process [(confirm)]="confirm" [(submittedBy)]="submittedBy"
            [createProjectSubResponseFunction]="createProjectSubResponseFunction">
        </app-q-sub-subsequent-process>
    </div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...