[英]Why is @Input property undefined in ngOnInit?
在這個組件中,我使用服務從 API 獲取一些數據
@Component({
selector: 'app-question-presenter',
template: `
<div class="question-presenter">
<app-question [question]="question"></app-question>
</div>
`
})
export class QuestionPresenterComponent implements OnInit {
private requestId: string;
private userId: string;
private question: Question;
constructor(
private route: ActivatedRoute,
private router: Router,
private questionService: QuestionService
) { }
ngOnInit() {
this.route.params.pipe(
switchMap((params: Params) => {
return this.questionService.getQuestion(params.requestId);
})
).subscribe((data: any) => this.question = data.data[0].question);
}
}
在另一個組件(提供app-question
)中,我試圖訪問question
但在控制台中undefined
。
@Component({
selector: 'app-question',
templateUrl: './question.component.html',
styleUrls: ['./question.component.scss']
})
export class QuestionComponent implements OnInit {
@Input()
question: Question;
constructor() {}
ngOnInit() {
console.log(this.question);
}
我知道數據正在進入模板(因為它按預期呈現)但我認為Input
將在調用ngOnInit
之前加載 - 我做錯了什么?
您可以延遲組件的創建,直到值准備好。
<app-question *ngIf="question" [question]="question"></app-question>
您還可以使用可觀察的
this.question$ = this.route.params.pipe(
switchMap(({requestId) => this.questionService.getQuestion(requestId))
)
然后在模板中:
<app-question *ngIf="question$ | async as question" [question]="question"></app-question>
看起來你有一個競爭條件。 如果您擔心它僅顯示在模板上,您可以向要綁定的屬性添加一個異步管道。 它只會在屬性具有值時顯示。 這將訂閱問題屬性並適當取消訂閱。
html
<div>
<p>{{question | async }}</p>
</div>
如果您希望在組件本身中使用該變量,我會訂閱您的 QuestionPresenterComponent 中的 question 屬性。
為了使它更簡潔,我建議將該變量與您的 API 調用一起放在共享服務中,這樣所有訂閱者都會相應地繼承更新。
@Component({
selector: 'app-question',
templateUrl: './question.component.html',
styleUrls: ['./question.component.scss']
})
export class QuestionComponent implements OnInit {
@Input()
question: Question;
constructor(private sharedService: SharedService) {}
ngOnInit() {
this.sharedService.question.subscribe(question => {
console.log(question)
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.