将值从父级传递给子级。子组件中收到的值未定义working example
这是我的app.component
import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
interface ItemsResponse {
data: any[];
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
constructor(private http: HttpClient) {}
ngOnInit() {
this.getPosts();
console.log( this.name); // name is undefined
}
name;
results:Array<any> = []; // code changed
getPosts() {
this.http.get<ItemsResponse>('https://reqres.in/api/users?page=3').subscribe(res =>
this.name = res); // code changed
}
}
这是我的hello组件,其中数据被传递给子组件 正如您所看到的,通过angular的@input装饰器从父组件传递到子组件的名称在构造函数中是未定义的。
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `<pre>{{name | json}}</pre>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
}
和Hello.component
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `<h1>hi</h1><pre>{{name | json}}</pre>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
ngOnInit() {
console.log('name', this.name); // name is undefined
}
@Input() name: string;
}
答案 0 :(得分:7)
首先,您的代码是异步的,因此您的console.log需要位于subscribe:
中.subscribe(res => {
this.name = res
console.log(this.name);
})
请查看此信息以获取更多信息:How do I return the response from an Observable/http/async call in angular2?
其次,您希望将对象传递给您的孩子,而不是
<hello name="{{ name }}"></hello>
你想做的事:
<hello [name]="name"></hello>
<强> DEMO 强>
由于这是异步的,name
最初将是未定义的,因为响应需要一些时间。您可以在子项中使用OnChanges
来跟踪值何时到达。只要OnChanges
值发生变化,就会触发@Input
。所以你可以有条件地检查价值是否存在,当它出现时,做你需要做的任何事情。
ngOnChanges() {
if(this.name) {
console.log(this.name)
}
}
https://stackblitz.com/edit/angular-rpc1vy?file=app/hello.component.ts