ng2學習筆記一

一、依賴注入在 Angular2 中,一個常見的依賴注入是注入一個 Http 對象,用於發送請求。

import {Component, OnInit} from 'angular2/core';  
import {Http} from 'angular2/http';//從 angular2/http 中將 Http import 進來


@Component({
  selector: 'test',
  providers: [Http]//在組件的配置中添加對應的 providers
})
class Test implements OnInit {  
  constructor(private http: Http) {//在 constructor 中聲明一個參數
  }


  ngOnInit() {
    this.http.get('/api/user.json').map(res => res.json()).subscribe(result => {
      // 這裏拿到請求的結果
    });
  }
}

上述代碼是在 Angular 中使用內置 Http 模塊發送請求的一段示例代碼。具體依賴注入發生在 constructor 函數中。按照 Angular 宣傳的那樣,你只用簡單的在 constructor 中聲明這些參數,Angular 將自動爲你處理依賴注入的問題。

注意到我們要使用 Http 來發請求,首先需要從 angular2/http 中將 Http import 進來,然後需要在組件的配置中添加對應的 providers,最後還需要在 constructor 中聲明一個參數。

二、組件通信

在 Angular 中,父組件想要傳遞一些信息給子組件,還是比較簡單的,直接使用屬性綁定即可。在子組件中稍微麻煩一點,多聲明一個 @Input


這裏還想吐槽兩句,一個組件想要引用另一個組件要先 import 進來然後還要加到當前組件 Component 配置的 directives 屬性中。開發過程中好多次莫名其妙的報錯都是因爲忘了這一步……

// Parent.js
@Component({
  selector: 'parent',
  template: `
    <h1>Parent</h1>
    <child [data]="data"></child>
  `
})
class Parent {  
  data = 'react';
}

// Child.js
@Component({
  selector: 'child',
  template: `
    <h4>Child</h4>
    <p>Data from parent: {{ data }}
  `
})
class Child {  
  @Input() data;
}


這個時候問題來了,當子組件發生某些變化父組件想要知道的時候,你有這麼幾種選擇。


1、在子組件中定一個 @Output 屬性,然後父組件用 (event)="handler()" 的語法來監聽這個事件
2、將父組件的一個 event handler 當做屬性傳給子組件,子組件通過調用這個方法來通知父組件(在 Redux 裏,這很常見)(更新的官方文檔裏明確說明了不提倡使用這樣的方式
3、設計一個 Service 然後分別注入到父組件和子組件之中進行通信


在我開發這個項目的時候,Angular2 的官方文檔中還沒有任何教程說明組件之間溝通該如何進行(現在 有了 ),所以我果斷選擇了最 Redux 的那種。


結果發現,後來更新的官方文檔裏明確說明了不提倡使用這樣的方式


我只能說很心累……

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