[Angular 2] 9. Value Providers & @Inject

Dependecies aren’t always objects created by classes or factory functions. Sometimes, all we really want is inject a simple value, which can be a primitive, or maybe just a configuration object. For these cases, we can use value providers and in this lesson we’ll discuss, how they are created.

For example we have this code:

import {LoggerProvider} from ‘./LoggerProvider‘;import (Http) from ‘@angular/http‘;
import {Injectable} from ‘@angular/core‘;

@Injectable
export class TodoService{

    apiUrl : string = "http://localhost:3000/api"

    constructor(private logger: LoggerProvider, private http: Http){ }

    getTodos(){
        this.logger.debug(‘Items‘, this.todos);
        return this.http.get(`${this.apiUrl}/todos`).map(res => res.json());
    }
}

Code use hard coded ‘apiUrl‘ to get data from backend. It would be better to inject apiUrl instead of hard coded.

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‘
    }
], 

Inside providers we add another value provider. Using keyword ‘useValue‘.

Then in the TodoService, we can do:

import {LoggerProvider} from ‘./LoggerProvider‘;
import {Injectable} from ‘@angular/core‘;import {Http} from ‘@angular/core‘;
import {Inject} from ‘@angular/core‘;

@Injectable
export class TodoService{

    constructor(@Inject(apiUrl) 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());
    }
}

We add @Inject because ‘apiUrl‘ doesn‘t have annotation for ‘apiUrl‘.  Angular provide @Inject for this case. @inject is a decorator that we can attach to the constructor parameter so we can annotate them with the required metadata.

Another thing to note is that @inject takes any token, not just strings.

We can also do:

constructor(@Inject(apiUrl) private apiUrl, @Inject(LoggerProvider) private logger, private http: Http){ }

This is useful if we happen to write our Angular 2 application in a language other than TypeScript, where type annotations don‘t exist.

时间: 2024-10-23 09:30:39

[Angular 2] 9. Value Providers & @Inject的相关文章

Angular 4+ HttpClient

这篇,算是上一篇Angular 4+ Http的后续: Angular 4.3.0-rc.0 版本已经发布??.在这个版本中,我们等到了一个令人兴奋的新功能 - HTTPClient API 的改进版本: HttpClient 是已有 Angular HTTP API 的演进,它在一个单独的 @angular/common/http 包中.这是为了确保现有的代码库可以缓慢迁移到新的 API: 大多数前端应用都需要通过 HTTP 协议与后端服务器通讯.现代浏览器支持使用两种不同的 API 发起 H

angular 4--指令笔记

1. Angular 模块引导 Angular没有了类似AngularJS中的<body ng-app="my-app">这样的引导指令了 通过显示调用 bootstrap 函数,并传入应用模块的名字( AppComponent)来启动应用. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComp

解决使用angular2路由后,页面刷新后报404错误。

点击路由链接跳转页面是正常的,但是当刷新页面时就出现了404错误. 解决方法如下: 在app.module.ts中添加import: import {HashLocationStrategy,LocationStrategy} from '@angular/common'; 并在 providers下添加所引入的服务: providers: [{provide: LocationStrategy,useClass: HashLocationStrategy}] 备注:出现问题的原因:刷新页面时寻

用ng-view创建单页APP

我们假设我们有一个单页面的程序,并且想为这个页面添加动画效果.点击某一个链接会将一个试图滑出,同时将另一个试图滑入. 我们将会使用: 使用 ngRoute 来为我们的页面路由 使用 ngAnimate 来为页面创建动画效果 对页面使用 CSS Animations 当我们离开或进入试图时,我们的每一个页面会有不同的动画效果 让我们看一下ngAnimate是如何工作的.ngAnimate 会根据是进入还是离开视图来为不同的Angular 指令(directive)添加和移除不同的CSS类名.例如,

AngularJs学习笔记--Dependency Injection(DI,依赖注入)

原版地址:http://code.angularjs.org/1.0.2/docs/guide/di 一.Dependency Injection(依赖注入) 依赖注入(DI)是一个软件设计模式,处理代码如何得到它所依赖的资源. 关于DI更深层次的讨论,可以参观Dependency Injection(http://en.wikipedia.org/wiki/Dependency_injection),Inversion of Control(http://martinfowler.com/ar

[Angular 2] 5. Inject Service with &quot;Providers&quot;

In this lesson, we’re going to take a look at how add a class to the providers property of a component creates an actual providers. We’ll learn what a provider specifically does and how we can provide different dependencies with the same token. impor

Angular之Providers (Value, Factory, Service and Constant )

官方文档Providers Each web application you build is composed of objects that collaborate to get stuff done.(每一个web应用都是由一些对象“组装”成的,这些对象共同合作,来完成特定的任务)These objects need to be instantiated and wired together for the app to work.(这些对象需要被实例化,然后“组装”在一起来使web应用能

[Angular] Difference between Providers and ViewProviders

For example we have a component: class TodoList { private todos: Todo[] = []; add(todo: Todo) {} remove(todo: Todo) {} set(todo: Todo, index: number) {} get(index: number) {} getAll() {} } @Component({ // ... viewProviders: [TodoList] // ... }) class

[Angular 2] BYPASSING PROVIDERS IN ANGULAR 2

Artical --> BYPASSING PROVIDERS IN ANGULAR 2 Here trying to solve one problem: On the left hand side of tree, there are 4 green blocks and 1 blue block. Meaning that three green dataService will use 'OtherProvider' which in an instance of DataService