When using provider string tokens, there’s a chance they collide with other third-party tokens. Angular has with the concept of opaque tokens, that allow us to make whatever token we use unique, so we don’t run into collision problems. In this lesson we’ll explore how they work.

We created a value provide like this:
 providers: [
TodoService,
ConsoleService,
TranslateService,
,{
provide: LoggerProvider, useFactory: (cs, ts) => {
return new LoggerProvider(cs, ts, true)
},
deps: [ConsoleService, TranslateService]
}
,{
provide: apiUrl,
useValue: 'http://localhost:3000/api'
}
],

It turns out that this can be problematic in case we're using, for example, a third-party library that comes with its own provider that introduces the same token.

third-party.ts:

export const THIRD_PARTY_PRIVODERS = [
{
provide: apiUrl,
useValue: 'someurl'
}
]

So when you inject third-pary library into our app.ts:

 providers: [
TodoService,
ConsoleService,
TranslateService,
,{
provide: LoggerProvider, useFactory: (cs, ts) => {
return new LoggerProvider(cs, ts, true)
},
deps: [ConsoleService, TranslateService]
}
,{
provide: apiUrl,
useValue: 'http://localhost:3000/api'
}
,THIRD_PARTY_PROVIDERS
],

Then it will rewrite our 'apiUrl' because THIRD_PARTY_PROVIDERS comes behind apiUrl.

To solve this problem, Angular introduce OpaqueToken.

app.tokens.ts:

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

export const API_URL = new OpaqueToken('apiUrl')

Now 'API_URL' is a class instance not just a string, class instance is always unique.

Then in app.ts:

import {API_URL} from './app.tokens' 

providers: [
TodoService,
ConsoleService,
TranslateService,
,{
provide: LoggerProvider, useFactory: (cs, ts) => {
return new LoggerProvider(cs, ts, true)
},
deps: [ConsoleService, TranslateService]
}
,{
provide: API_URL,
useValue: 'http://localhost:3000/api'
}
,THIRD_PARTY_PROVIDERS
],

In DataService:

import {LoggerProvider} from './LoggerProvider';
import {Injectable} from '@angular/core';
import {Http} from '@angular/core';
import {Inject} from '@angular/core';
import {API_URL} from './app.tokens'; @Injectable
export class TodoService{ constructor(@Inject(API_URL) private apiUrl, private logger: LoggerProvider, private http: Http){ } getTodos(){
this.logger.debug('Items', this.todos);
return this.http.get(`${this.apiUrl}/todos`).map(res => res.json());
}
}

Now we won't have conflict anymore.

As a general rule, always create opaque tokens when using string tokens for providers. For example:

third-party.ts:

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

const API_URL = new OpaqueToken('apiUrl');
const CONFIG_URL = new OpaqueToken('configUrl'); export const THIRD_PARTY_PROVIDERS = [
{
provide: API_URL,
useValue: 'somevalue'
},
{
provide: CONFIG_URL,
useValue: 'somevalue'
}
]

[Angular 2] Understanding OpaqueToken的更多相关文章

  1. [Angular 2] Understanding Pure & Impure pipe

    First, how to use a build in pipe: <div class="pipe-example"> <label>Uppercase ...

  2. [Angular 2] Understanding @Injectable

    In order to resolve a dependency, Angular’s DI uses type annotations. To make sure these types are p ...

  3. 来自 Thoughtram 的 Angular 2 系列资料

    Angular 2 已经正式 Release 了,Thoughtram 已经发布了一系列的文档,对 Angular 2 的各个方面进行深入的阐释和说明. 我计划逐渐将这个系列翻译出来,以便对大家学习 ...

  4. angular default project (angular.json的解读)

    Change the default Angular project Understanding it's purpose and limits Klaus KazlauskasFollow Nov ...

  5. Angular 4+ 修仙之路

    Angular 4.x 快速入门 Angular 4 快速入门 涉及 Angular 简介.环境搭建.插件表达式.自定义组件.表单模块.Http 模块等 Angular 4 基础教程 涉及 Angul ...

  6. Angular复习笔记6-依赖注入

    Angular复习笔记6-依赖注入 依赖注入(DependencyInjection)是Angular实现重要功能的一种设计模式.一个大型应用的开发通常会涉及很多组件和服务,这些组件和服务之间有着错综 ...

  7. angular2 学习笔记 ( DI 依赖注入 )

    refer : http://blog.thoughtram.io/angular/2016/09/15/angular-2-final-is-out.html ( search Dependency ...

  8. AngularJs学习笔记--Understanding Angular Templates

    原版地址:http://docs.angularjs.org/guide/dev_guide.mvc.understanding_model angular template是一个声明规范,与mode ...

  9. 【转】Understanding the Angular Boot Process

    原文: https://medium.com/@coderonfleek/understanding-the-angular-boot-process-9a338b06248c ----------- ...

随机推荐

  1. JAVA深复制(深克隆)与浅复制(浅克隆)

    1.浅复制与深复制概念⑴浅复制(浅克隆)被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用仍然指向原来的对象.换言之,浅复制仅仅复制所考虑的对象,而不 复制它所引用的对象. 1. ...

  2. Reading or Writing to Another Processes Memory in C# z

    http://www.jarloo.com/reading-and-writing-to-memory/ Declarations [Flags] public enum ProcessAccessF ...

  3. ie对行高line-height的诡异解释

    切 游戏页面真地是要求太精细了,做按钮的时候我犯了一个错误,居然用span的内联元素的行高和padding来控制,虽然有很多好处,但是IE对 line-height的解释导致按钮经常下边会缺一小部分, ...

  4. Qt Style Sheets制作UI特效

    使用Qt Style Sheets制作UI特效  博客出处:http://developer.nokia.com/community/wiki/%E4%BD%BF%E7%94%A8Qt_Style_S ...

  5. hadoop 权限错误 Permission denied: user=root, access=WRITE, inode="/":hdfs:super

    关于不能执行Hadoop命令 并报权限问题执行错误1.Permission denied: user=root, access=WRITE, inode="/":hdfs:supe ...

  6. sudo source /etc/profile 提示找不到source命令

    今天修改了/etc/profile,需要用source一下,于是写入命令 sudo source /etc/profile 提示找不到source命令 改成    sudo . /etc/profil ...

  7. Cloudera CDH5 部署实战指南(离线安装)

    配置软件源服务器 1.安装createreporpm -ivh deltarpm-3.5-0.5.20090913git.el6.x86_64.rpm rpm -ivh python-deltarpm ...

  8. Windows7 32位下opencv与python2.66的环境配置

    刚接触Python和OpenCV,对两者都不太了解,因为今后学习会使用到这两种工具,特此学习配置.PS:本帖适用小白. 一. 需要的文件 1. OpenCV 可用OpenCV-2.3.1-win-su ...

  9. Apache Rewrite常用设置说明

    例子: RewriteEngine on 打开引擎 RewriteRule test.html /test.php [L] RewriteRule test.html?$ /tianqi.php?s1 ...

  10. web.py实现jsonp

    浏览器端请求 $.getJSON("/currenttime?callback=?", function (json){ $("#time").html(jso ...