Kar*_*rty 4 angular-cli angular
将值从父级传递给子级.子组件中接收的值是未定义的工作示例
这是我的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
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的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;
}
Run Code Online (Sandbox Code Playgroud)
并在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;
}
Run Code Online (Sandbox Code Playgroud)
首先,您的代码是异步的,因此您的console.log需要在订阅中:
.subscribe(res => {
this.name = res
console.log(this.name);
})
Run Code Online (Sandbox Code Playgroud)
请检查以获取更多信息:如何从angular2中的Observable/http/async调用返回响应?
其次,您希望将对象传递给您的孩子,而不是
<hello name="{{ name }}"></hello>
Run Code Online (Sandbox Code Playgroud)
你想做的事:
<hello [name]="name"></hello>
Run Code Online (Sandbox Code Playgroud)
由于这是异步的,name因此最初将是未定义的,因为它需要一些时间来响应.您可以OnChanges在子项中使用它来跟踪值何时到达.OnChanges只要@Input值发生变化就会被触发.所以你可以有条件地检查价值是否在那里,当它存在时,做你需要做的任何事情.
ngOnChanges() {
if(this.name) {
console.log(this.name)
}
}
Run Code Online (Sandbox Code Playgroud)
https://stackblitz.com/edit/angular-rpc1vy?file=app/hello.component.ts
| 归档时间: |
|
| 查看次数: |
3687 次 |
| 最近记录: |