我目前正在尝试在angular 9中创建一个动态菜单。由于某些原因,我是angel的新手,并收到以下错误消息: “无法解析C:/mypath/head-menu.component.ts:(?,?,?)中HeadMenuComponent的所有参数的错误。”代码很简单:
import { Component, OnInit, Inject, Injectable } from '@angular/core';
@Component({
selector: 'app-head-menu',
templateUrl: './head-menu.component.html',
styleUrls: ['./head-menu.component.css']
})
export class HeadMenuComponent implements OnInit {
imageURL: string;
text: string;
menuFunction: () => void;
constructor(@Inject(String)imageURL: string, @Inject(String)text: string,
@Inject(Function)functionToAccept: () => void) {
this.imageURL = imageURL;
this.text = text;
this.menuFunction = functionToAccept;
}
ngOnInit(): void {
}
}
代码正在编译,可以执行ng serve,但是我仍然收到错误消息。这对我来说尤其重要,因为由于该错误,angular-cli命令:ng xi18n无法运行。
所以我的问题是:“我做错了什么?”还有另一种将对象传递给构造函数的方法吗?使用角注入,只是将字符串传递给构造函数,这对我来说是错误的,但是我还没有找到其他方法。
答案 0 :(得分:1)
执行此操作的一种方法是执行以下操作:
export const IMAGE_URL = new InjectionToken<string>('imageUrl');
然后,在app.module
(或其他位置)中
{
provide: IMAGE_URL ,
useValue: 'www.someurl.com'
}
或
{
provide: IMAGE_URL,
deps: [ConfigService], //dependencies
useFactory: (c: ConfigService) => {
return c.someUrlValue();
}
}
然后食用:
constructor(@Inject(IMAGE_URL) imageUrl: string) {
}