[Angular] Using InjectionToken

Previously we have 'OpaqueToken', but it is DEPRECATED. The new one is called 'InjectionToken'.

The difference between OpaqueToken is for InjectionToken we are able to pass the type, but OpaqueToken not.

 

// token.ts

import { InjectionToken } from '@angular/core';

export const API_TOKEN = new InjectionToken<string>('api');
//app.module.ts

  providers: [
    { provide: API_TOKEN, useValue: '/api/pizzas' }
  ]
// service.ts

import { API_TOKEN } from './token';

@Injectable()
export class FoodService {
  constructor(
    private http: Http,
    @Inject(API_TOKEN) private api: string
  ) {}
  getFood(): Observable<any[]> {
    return this.http.get(this.api)
      .map(response => response.json());
  }
}

 

posted @ 2017-05-11 01:35  Zhentiw  阅读(898)  评论(0编辑  收藏  举报