加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular @input值未定义

发布时间:2020-12-17 17:23:47 所属栏目:安全 来源:网络整理
导读:将值从父级传递给子级.子组件中接收的值未定义 working example 这是我的app.component import { Component,OnInit } from '@angular/core';import {HttpClient} from '@angular/common/http';interface ItemsResponse { data: any[];}@Component({ selector
将值从父级传递给子级.子组件中接收的值未定义 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,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;
}

working example

解决方法

首先,您的代码是异步的,因此您的console.log需要在订阅中:

.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

由于这是异步的,因此名称最初将是未定义的,因为响应需要一些时间.您可以在子项中使用OnChanges来跟踪值何时到达.只要@Input值发生变化,就会触发OnChanges.所以你可以有条件地检查价值是否在那里,当它出现时,做你需要做的任何事情.

ngOnChanges() {
  if(this.name) {
    console.log(this.name)
  }
}

https://stackblitz.com/edit/angular-rpc1vy?file=app/hello.component.ts

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读