【问题标题】:Angular2 EXCEPTION No provider for StringAngular2 EXCEPTION 没有字符串的提供者
【发布时间】:2017-06-12 11:07:43
【问题描述】:

我用 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

【问题讨论】:

标签: angular typescript ionic3


【解决方案1】:

构造函数错误:

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

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

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() {}
}

【讨论】:

  • 这是一个有效的语法,它与角度本身无关
  • 但总而言之 AppComponent 是一个类 - 组件和类有什么不同? imo 角度 di 应该知道参数是一个字符串
  • @Whisher 它知道它是一个字符串。它不知道应该是哪个字符串。因此出现错误。
  • 作为类型的字符串是字符串,所以我等待相同的普通 ts 行为
  • @Whisher 为了缩短事情的篇幅并大大简化,@Component 装饰器告诉 AppComponent 不是一个“普通”类,而是一个组件。在这种情况下,您必须告诉 string 是您的组件的提供者,因为它期望在构造函数中注入的内容应该是提供者,因此在您的组件或 ngModule 中的 providers: [string] 中声明。 “字符串”不起作用,因为它不是已知的 Angular 2 提供程序,除非您创建一个名为 string 的服务(或其他),并且其中包含 Angular 魔法;)如前所述,这只是一个简化的示例。
【解决方案2】:

我遇到了这个错误,可以解决它

只需要重新运行构建过程

通过 cntrl+c 停止它

又是ionic serve

或角度命令

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 2018-06-14
    • 2016-04-06
    • 2017-01-31
    • 2017-07-30
    • 1970-01-01
    • 2016-12-18
    • 2016-07-06
    • 1970-01-01
    相关资源
    最近更新 更多