Angular 中間部分 2.2 依賴注入和Http

依賴注入 DI (Dependency Injection) system

依賴:當模塊a需要模塊b才能運行時,模塊b是模塊a的依賴。

p192, p169

Dependency Injection Parts

註冊一個依賴時,需要綁定到sth識別這個依賴。
識別就是 token。
依賴注入 3個部分
1,provider,把新的實例,註冊在這裏,就可以提供給注入器
2,injector 注入器 保存之前創造的實例,如果沒有請求的實例,會創建一個並添到注入器中,通過provider,
3,dependecy 被注入

註冊依賴,在provider中,描述依賴被如何注入,注入
組件與組件之間的運用

p174 標準做法
- 用 NgModule 註冊需要注入的 也就是providers
- 用裝飾 decorators (通常在 constructor) 定義注入內容

在NgModule註冊
user-demo/user-demo.module.ts

import { UserService } from '../services/user.service';

@NgModule({
  imports: [
    CommonModule
  ],
  providers: [
    UserService // <-- added right here
  ],
  declarations: []
})

注入組件 在constructor中導入 p195, p198
user-demo.component.ts

export class UserDemoComponent {
  userName: string;

  constructor(private userService: UserService) {
  }

本質上就是註冊 provider:[],注入(導入)?
正確的註冊 provider 很關鍵

providers: [ UserService ]
就是告訴Angular 當UserService注入時,提供一個單個實體(singleton instance ——
默認class就是UserService
等於:

providers: [
  { provide: UserService, useClass: UserService }
]

provide 是token用來identify
useClass 是how and what to inject
provide相當於全局開放UserService class 和這個UserServiceg token

當第一個注入時,也就是第一次實體產生時,DI會觸發constructor。

當有API的URL是,
註冊

providers: [
  { provide: 'API_URL', useValue: 'http://my.api.com/v1' }
]

注入時,不能直接寫

constructor(apiUrl: 'API_URL') {

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

export class AnalyticsDemoComponent {
  constructor(@Inject('API_URL') apiUrl: string) {

  }
}

p178 p201 配置服務
記錄事件

useFactory p181 p204

HTTP

Angular使用內置HTTP庫來請求外部API
HTTP請求需要異步同步,JS通常用以下3中方法:
1, Callbacks
2, Promises
3, Observables
Angular用的是Observables來處理異步同步。

如何導入和啓用HttpModule p187 p210

通過注入方式啓用

@angular/http導入HttpModule

app.module.ts 註冊並導入

import { HttpModule } from '@angular/http';
...

@NgModule({
  declarations: [
  ...],

  imports: [
    ...
    HttpModule
  ],

在組件中注入

import {Http, Response} from '@angular/http';

class MyFooComponent { 
  constructor(public http: Http) {
  }

  makeRequest(): void {
    ...
  }
}

request API連接 p189 p212

在component導入對應的組件後,
使用一個get API request
組件controller寫法如下

import { Component, OnInit } from '@angular/core';
import {Http, Response} from '@angular/http'; //導入

@Component({
  selector: 'app-simple-http',
  templateUrl: './simple-http.component.html'
})
export class SimpleHttpComponent implements OnInit {
  data: Object;
  loading: boolean;

  constructor(private http: Http) { //局部注入
  }

  ngOnInit() {
  }

  //api get request
  makeRequest(): void { 
    this.loading = true;
    this.http.request('http://jsonplaceholder.typicode.com/posts/1')
    .subscribe((res: Response) => {
      this.data = res.json();
      this.loading = false;
    });
  }
}

this.http.request()發送GET請求
http.request 返回的是 Observable(會在後面數據結構講)
通過subscribe進行改變
this.data = res.json();
get會返回一個responce對象,通過提取這個對象的body並且轉化成json格式。
賦予目標對象this.data
並且把laoding設爲false

在html中啓用

<h2>Basic Request</h2>
<button type="button" (click)="makeRequest()">Make Request</button>
<div *ngIf="loading">loading...</div> //綁定loading
<pre>{{data | json}}</pre> //轉化json格式?

YouTube 探索組件 p193 p215

探索,出現結果。需要如下組件p216 p194
- searchResult : hold the search date
- YouTubeSearchService: mangage the API request
- SearchBoxComponent: use the Youtube service
- SearchResultComponent: 渲染結果模版
- YouTubeSearchComponent: 父組件,渲染list of results

@angular/http API p212 p235

posy request

RequestOptions

• method
• headers
• body
• mode
• credentials
• cache
• url
• search

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章