Angular2 异常没有字符串提供者

标签 angular typescript ionic3

我用 ng-cli 创建了一个全新的应用程序 用这个非常简单的代码^^

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private my: string) {}
} 

我已经进入了控制台

异常:没有字符串的提供者!

我没有看到代码中有任何错误,所以 怎么了!

在 ng-book 中我可以阅读

export class Article { 
  title: string; 
  link: string; 
  votes: number;
  constructor(title: string, link: string, votes?: number) { 
    this.title = title;
    this.link = link;
    this.votes = votes || 0;
  }
}

看看

https://github.com/Microsoft/TypeScriptSamples/blob/master/greeter/greeter.ts

最佳答案

构造函数错误:

export class AppComponent {
  constructor(private my: string) {}
} 

private my: string 不应注入(inject)到构造函数中,而是注入(inject)到外部,这里假设它是您要在组件中使用的变量。

export class AppComponent {
  private my: string;
  constructor() {
    this.my = 'Hello!'; // if you want to assign a value (in the constructor) to your string, do it here!
  }
} 

我建议您从 Tutorial 开始从头开始学习 Angular 的基础知识 :)

编辑,您添加的后半部分是一个类,例如用于键入您的对象,而不是组件,对于文章类的类型化对象,这是有效的语法:

export class Article { 
  title: string; 
  link: string; 
  votes: number;
  constructor(title: string, link: string, votes?: number) { 
    this.title = title;
    this.link = link;
    this.votes = votes || 0;
  }
}

然后您可以将此类导入您的AppComponent,并用于分配一个Article对象。

import { Component } from '@angular/core';
import { Article } from './your.path'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  article: Article = new Article('titleHere', 'linkHere', 3)

  constructor() {}
}

关于Angular2 异常没有字符串提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41882599/

相关文章:

angular - Angular Dart教程第4部分- 'Future not resolved'

json - 从 API 中解析 JSON 字符串

Angular 9 取消 HTTP 请求

css - 通过 Angular 路由器导航后导航不关闭

javascript - typescript 推送到数组中的特定键

javascript - 无法从 Firebase 下载数据 - TypeError : undefined is not an object

cordova - Ionic 2/iOS - native 音频在 cordova.file.dataDirectory 中找不到文件

ionic-framework - 在模块 ts 中输入提供程序时出错

javascript - 如何在 Ionic 3 中搜索数组项?

html - Angular 2 : how to clear the dropdown and textbox values while switching the radio buttons