【问题标题】:value is undefined when passed in component in angular 6以角度 6 传入组件时,值未定义
【发布时间】:2019-05-20 13:25:16
【问题描述】:

我有一个调用 API(Http 获取请求)的服务,然后我在我的组件中调用该服务来获取数据,然后将其分配给一个值。之后我将 html 中的值传递给另一个组件,但它显示为未定义

import { Component } from '@angular/core';
import { AuthService } from '../../src/app/services/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  passData: any
  constructor(private authService: AuthService) {
  }
  ngOnInit() {
    this.authService.test().subscribe(data => {
      for (var i = 0; i < data.length; i++) {
            data[i].date = new Date(
            data[i].date.substring(0, 4)+'-'+
            data[i].date.substring(4, 6)+'-'+
            data[i].date.substring(6, 10)+ ' '+data[i].minute)
          }
          this.passData = data;
    });
  }

}

下面是我将值传递给新组件的地方,但显示未定义

<div class="card-deck">
   <app-stock-bar  [customTitle]=passData></app-stock-bar>

传递时passData的值是未定义的,但是如果我记录它,它会在控制台中显示该值

【问题讨论】:

  • 试试这个 -
  • 不,这不是正确的做法
  • 对象数组
  • 显示 authService.test() 的代码并阐明什么是 customTitle?
  • 我们需要看到新组件app-stock-bar

标签: node.js angular api angular6


【解决方案1】:

我认为属性绑定缺少双引号

 <app-stock-bar  [customTitle]="passData"></app-stock-bar>

【讨论】:

  • 我的意思是无论如何都不对。这不是您在 html 中传递值的方式。
【解决方案2】:

经过一番研究,答案很简单,我发现您可以简单地使用 *ngIF 在加载之前检查该值是否存在

    <app-stock-bar  *ngIf="passData"  [customTitle]="passData"></app-stock-bar>

【讨论】:

    【解决方案3】:

    当您将值从父组件传递到子组件时。您可以在 onChanges LifeCycle 挂钩中访问它。

    组件

    @Component({})
    export class AppStockBar implements OnChanges{
    
      @Input() customTitle;
      ngOnChanges(){
        console.log(this.customTitle);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-08
      • 2019-02-25
      • 2018-04-12
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 2018-08-14
      相关资源
      最近更新 更多