[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());
  }
}

 

Related Posts

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注