为可注入服务构造函数提供可选参数-Angular2

providing optional param to injectable service constructor - Angular2

有AppComponent和SecurityService。

...
@Injectable()
export class SecurityService implements OnInit {    
    private _url: string;

    constructor(private http: Http, private name?: string) {
        this._wsUrl = 'http://myurl/' + this.name        
    }
...
}

AppComponent 是一个将注入安全服务的组件。

export class App {

    constructor(private security: SecurityService){

    }
    ... 
}

My question is: How can I provide this optional param value for the security service constructor?

只需在构造函数参数前添加 @Optional() 装饰器,只有在提供程序已注册时才应注入该装饰器。

constructor(private http: Http,@Optional() private name: string) 

您可以在此处阅读有关 Optional 的更多信息

DEMO