小编Tom*_*asi的帖子

为什么在这个angular2示例中我仍然需要@inject?

这可能是一个特殊情况(注入浏览器本机窗口对象),但是当我的类已经有一个@Injectable()装饰器时,我仍然有点困惑为什么我仍然需要@Inject()参数装饰器.

举个简单的例子:

import { provide, bootstrap, Injectable, Inject } from '@angular/core';


@Injectable()
export class Token {
  private token: string;

  public constructor(token: string, window: Window) {
    this.token = window.atob(token);
  };

  public getToken(): string {
    return this.token;
  }
}


@Injectable()
export class TokenFactory {
  private window: Window;

  public constructor(window: Window) {
    this.window = window;
  }

  public createToken(token: string): Token {
    return new Token(token, this.window);
  }
}


@Component({
  template:   `
    <p *ngFor="let token of tokens">
      Encoded: {{token.getToken()}}
    </p>
  `,
  providers:  [ TokenFactory ] …
Run Code Online (Sandbox Code Playgroud)

dependency-injection factory-pattern angular

2
推荐指数
1
解决办法
364
查看次数