EXCEPTION没有字符串提供程序

EXCEPTION没有字符串提供程序

本文介绍了Angular2 EXCEPTION没有字符串提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a brand new app create with a ng-cliwith this very simple code ^^

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

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

我已经进入控制台

例外:没有String提供商!

我在代码中看不到任何错误,因此怎么了!

I don't see any error in the code sowhat's wrong !

在ng书中我可以阅读

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不应注入到构造函数中,而应注入到外部,这里假定它是您要在组件中使用的变量.

private my: string should not be injected in the constructor, but outside, here assuming it's a variable you want to use in your component.

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!
  }
}

我建议您从 教程 开始从一开始就开始学习Angular的基础知识:)

I suggest you start of with the Tutorial from the beginning, so you learn the basics of Angular :)

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

EDIT, the latter part you added is a class e.g for typing your object, not a component, for a typed Object of class Article, this is valid syntax:

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对象.

Then you can import this class to your AppComponent, and use to assign an Article object.

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 EXCEPTION没有字符串提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:25