簡體   English   中英

Angular2 EXCEPTION沒有String的提供者

[英]Angular2 EXCEPTION No provider for String

我有一個全新的應用程序使用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) {}
} 

而且我已進入控制台了

EXCEPTION:沒有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不應該在構造函數中注入,但在外面,這里假設它是你想在組件中使用的變量。

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

我有這個錯誤,可以解決它

只需要重新運行構建過程

通過cntrl + c停止它

ionic serve再次ionic serve

或角度命令

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM