[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());
  }
}
原文地址:https://www.cnblogs.com/Answer1215/p/6839031.html