【问题标题】:Getting error on passing a variable through constructor通过构造函数传递变量时出错
【发布时间】:2018-08-29 12:40:18
【问题描述】:

当我在 Angular 中运行我的打字稿文件时,我在控制台中遇到错误

错误:compiler.js:215 未捕获错误:无法解析所有参数 对于 SearchNameComponent: ([object Object], ?)。

我正在发布我的完整代码

import { Component, OnInit } from '@angular/core';
import {StudentSearchService , Students} from '../service/student-search.service';
import DataSource from 'devextreme/data/data_source';


@Component({
  selector: 'app-search-name',
  templateUrl: './search-name.component.html',
  styleUrls: ['./search-name.component.css'],
  providers: [StudentSearchService],
})
export class SearchNameComponent implements OnInit {

  std: Students[];
  data: any = '';
  constructor( public students: StudentSearchService  , data: any) {

    this.std = students.getstudent();
    console.log(data);
}

  ngOnInit() {
  }

}

【问题讨论】:

  • Angular DI 在实例化组件时不知道您希望它为data 提供什么
  • 既然你有 data 作为一个属性,你不应该在构造函数中需要它。
  • 能否请您出示您的 StudentSearchService 文件,以便我为您提供帮助
  • 发布学生搜索服务代码

标签: javascript angular typescript ecmascript-6


【解决方案1】:

抛出错误是因为你定义了构造函数来接受 2 个参数,而只传递一个参数。

要么将第二个参数设为可选,要么从构造函数中删除第二个参数。

例子

export class SearchNameComponent implements OnInit {

  std: Students[];
  data: any = '';
  constructor( public students: StudentSearchService) {

    this.std = students.getstudent();
    console.log(data);
}

  ngOnInit() {
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 2020-03-18
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 2021-07-16
    相关资源
    最近更新 更多