我正在嘗試從建構式引數中設定默認值,并嘗試在 html 中列印。但得到錯誤
No suitable injection token for parameter 'name' of class 'AppComponent'.
Consider adding a type to the parameter or use the @Inject decorator to specify an injection token.
無法理解。任何人都在這里幫助我。我的代碼:
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor(public name = 'Angular') {} //default value moved with constructor
}
這里有什么問題或如何處理此類問題?如何引數化組件中的值?提前致謝。
現場演示
uj5u.com熱心網友回復:
您對引數屬性的嘗試將在Typescript中起作用。
export class AppComponent {
constructor(public name = 'Angular') {
const appDiv: HTMLElement = document.getElementById('app');
appDiv.innerHTML = name;
}
}
new AppComponent();
然而 Angular 對建構式引數有特殊的含義。Angular通過建構式引數采用依賴注入機制。要使用它,您需要注入一個可由組件使用的令牌。
- 一種用例是注入運行時配置常量。
- 另一個眾所周知的用例是使用
@Injectable()裝飾器使類可注入。更常見的是,它們被用作 Angular 服務。
基本示例:
import { Component, InjectionToken, Inject } from '@angular/core';
export const NAME = new InjectionToken<string>('');
@Component({
selector: 'my-app',
template: `<hello name="{{ name }}"></hello>`,
providers: [{ provide: NAME, useValue: 'Angular' }],
})
export class AppComponent {
constructor(@Inject(NAME) public name) {}
}
我已經調整了你的Stackblitz
或者,如果您不想涉足依賴注入,您可以放棄它并使用普通引數初始化。
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<hello name="{{ name }}"></hello>`,
})
export class AppComponent {
public name = 'Angular';
}
作業示例:Stackblitz
uj5u.com熱心網友回復:
您可以將組件類視為某種特殊的類,建構式應該用于 DI,例如注入服務。
例如,您可以為您的場景使用 @Input 并使用默認值。
如果你真的想這樣做,你應該創建一個將被注冊的可注入變數,以便 de DI 知道要注入什么,例如,為此你需要創建一個不透明的令牌。
const injectableToken= new OpaqueToken('token_name'); ...匯出類 AppComponent {建構式(@Inject(injectableToken)公共名稱:injectableToken){...}}
uj5u.com熱心網友回復:
我只是在這里為你做了一個例子
看看它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/431918.html
標籤:有角度的
