搜尋
首頁web前端js教程對angular的元件通訊的解析

對angular的元件通訊的解析

Jul 14, 2018 am 09:27 AM
csshtmlhtml5javascript

這篇文章主要介紹了關於對angular的元件通訊的解析,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

單頁應用元件通訊有以下幾種,這篇文章主要講Angular 通訊

對angular的元件通訊的解析

  1. #父元件=> 子元件

  2. 子元件=> 父元件

  3. 元件A = > 元件B

##@input@outputsetters (本質上還是@input)注入父元件ngOnChanges() (不建議使用)局部變數#@ViewChild()serviceserviceserviceRxjs的Observalbe#Rxjs的ObservalbeRxjs的ObservalbelocalStorage,sessionStoragelocalStorage,sessionStoragelocalStorage,localStorage,#Storage##sessionStorage##
父元件=>子元件 子元件=> 父元件 sibling  => sibling








localStorage,sessionStorage
####

上面圖表總結了能用到通訊方案,期中最後3種,是通用的,angular的組件之間都可以使用這3種,其中Rxjs是最最牛逼的用法,甩redux, promise,這些同樣基於函數式的狀態管理幾條街,下面一一說來

父元件=> 子元件

@input,最常用的一種方式

@Component({
  selector: 'app-parent',
template: '<p>childText:<app-child></app-child></p>',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  varString: string;
  constructor() { }
  ngOnInit() {
    this.varString = '从父组件传过来的' ;
  }
}
import { Component, OnInit, Input } from '@angular/core';
@Component({
  selector: 'app-child',
  template: '<h1 id="textContent">{{textContent}}</h1>',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Input() public textContent: string ;
  constructor() { }
  ngOnInit() {
  }
}

setter

setter 是攔截@input 屬性,因為我們在元件通訊的時候,常常需要對輸入的屬性處理下,就需要setter了,setter和getter常配套使用,稍微修改下上面的child.component.ts
child.component.ts

import { Component, OnInit, Input } from '@angular/core';
@Component({
  selector: 'app-child',
  template: '<h1 id="textContent">{{textContent}}</h1>',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
_textContent:string;
  @Input()
  set textContent(text: string){
   this._textContent = !text: "啥都没有给我" ? text ;
  } ;
  get textContent(){
  return this._textContent;
  }
  constructor() { }
  ngOnInit() {
  }
}

onChange

這個是透過angular生命週期鉤子來偵測,不建議使用,要使用的話可以參angular文檔

@ViewChild()

@ViewChild() 一般用在呼叫子元件非私有的方法

           import {Component, OnInit, ViewChild} from '@angular/core';
       import {ViewChildChildComponent} from "../view-child-child/view-child-child.component";
    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.css']
    })
    export class ParentComponent implements OnInit {
      varString: string;
      @ViewChild(ViewChildChildComponent)
      viewChildChildComponent: ViewChildChildComponent;
      constructor() { }
      ngOnInit() {
        this.varString = '从父组件传过来的' ;
      }
      clickEvent(clickEvent: any) {
        console.log(clickEvent);
        this.viewChildChildComponent.myName(clickEvent.value);
      }
    }
      import { Component, OnInit } from '@angular/core';
    @Component({
      selector: 'app-view-child-child',
      templateUrl: './view-child-child.component.html',
      styleUrls: ['./view-child-child.component.css']
    })
    export class ViewChildChildComponent implements OnInit {
      constructor() { }
      name: string;
      myName(name: string) {
          console.log(name);
          this.name = name ;
      }
      ngOnInit() {
      }
    }

局部變數

#局部變量和viewChild類似,只能用在html模板裡,修改parent.component.html,透過#viewChild這個變數來表示子元件,就能呼叫子元件的方法了.

<p>
    <input>
    <button>局部变量传值</button>
    <app-view-child-child></app-view-child-child>
            </p>

child 元件如下

@Component({
  selector: 'app-view-child-child',
  templateUrl: './view-child-child.component.html',
  styleUrls: ['./view-child-child.component.css']
})
export class ViewChildChildComponent implements OnInit {

  constructor() { }
  name: string;
  myName(name: string) {
      console.log(name);
      this.name = name ;
  }
  ngOnInit() {
  }

}

子元件=> 父元件

@output()

output這個常見的通訊,本質是給子元件傳入一個function,在子元件裡執行完某些方法後,再執行傳入的這個回呼function,將值傳給父元件

parent.component.ts
@Component({
  selector: 'app-child-to-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ChildToParentComponent implements OnInit {

  childName: string;
  childNameForInject: string;
  constructor( ) { }
  ngOnInit() {
  }
  showChildName(name: string) {
    this.childName = name;
  }
}

parent.component. html

<p>
  </p><p>output方式 childText:{{childName}}</p>
  <br>
  <app-output-child></app-output-child>
  child.component.ts
  export class OutputChildComponent implements OnInit {
  // 传入的回调事件
  @Output() public childNameEventEmitter: EventEmitter<any> = new EventEmitter();
  constructor() { }
  ngOnInit() {
  }
  showMyName(value) {
    //这里就执行,父组件传入的函数
    this.childNameEventEmitter.emit(value);
  }
}</any>

注入父元件

這個原理的原因是父,子元件本質生命週期是一樣的

export class OutputChildComponent implements OnInit {
  // 注入父组件
  constructor(private childToParentComponent: ChildToParentComponent) { }
  ngOnInit() {
  }
  showMyName(value) {
    this.childToParentComponent.childNameForInject = value;
  }
}

sibling元件=> sibling元件

service

Rxjs

透過service通訊

angular中service是單例的,所以三種通訊類型都可以透過service,很多前端對單例理解的不是很清楚,本質就是
,你在某個module中註入service,所有這個modul的component都可以拿到這個service的屬性,方法,是共享的,所以常在app.moudule.ts注入日誌service ,http攔截service,在子module注入的service,只能這個子module能共享,在component注入的service,就只能子的component的能拿到service,下面以注入到app.module.ts,的service來示範

user.service.ts
@Injectable()
export class UserService {
  age: number;
  userName: string;
  constructor() { }
}
app.module.ts
@NgModule({
  declarations: [
    AppComponent,
    SiblingAComponent,
    SiblingBComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [UserService],
  bootstrap: [AppComponent]
})
export class AppModule { }
SiblingBComponent.ts
@Component({
  selector: 'app-sibling-b',
  templateUrl: './sibling-b.component.html',
  styleUrls: ['./sibling-b.component.css']
})
export class SiblingBComponent implements OnInit {
  constructor(private userService: UserService) {
    this.userService.userName = "王二";
  }
  ngOnInit() {
  }
}
SiblingAComponent.ts
@Component({
  selector: 'app-sibling-a',
  templateUrl: './sibling-a.component.html',
  styleUrls: ['./sibling-a.component.css']
})
export class SiblingAComponent implements OnInit {
  userName: string;
  constructor(private userService: UserService) {
  }
  ngOnInit() {
    this.userName = this.userService.userName;
  }
}

透過Rx.js通訊

這個是最屌的,基於訂閱發布的這種流文件處理,一旦訂閱,發布的源頭發生改變,訂閱者就能拿到這個變化;這樣說不是很好理解,簡單解釋就是,b.js,c.js,d.js訂閱了a.js裡某個值變化,b.js,c.js,d.js立刻取得到這個變化的,但是a.js並沒有主動調用b.js,c.js,d.js這些裡面的方法,舉個簡單的例子,每個頁面在處理ajax請求的時候,都有一彈出的提示訊息,一般我會在
元件的template中放一個提示框的元件,這樣很繁瑣每個元件都要來一次,如果基於Rx.js,就可以在app.component.ts中放這個提示元件,然後app.component.ts訂閱公共的service,就比較省事了,代碼如下
先搞一個alset.service.ts

import {Injectable} from "@angular/core";
import {Subject} from "rxjs/Subject";
@Injectable()
export class AlertService {
  private messageSu = new Subject<string>();  //
  messageObserve = this.messageSu.asObservable();
  private  setMessage(message: string) {
    this.messageSu.next(message);
  }
  public success(message: string, callback?: Function) {
    this.setMessage(message);
    callback();
  }
}</string>

sibling-a.component.ts

@Component({
  selector: 'app-sibling-a',
  templateUrl: './sibling-a.component.html',
  styleUrls: ['./sibling-a.component.css']
})
export class SiblingAComponent implements OnInit {
  userName: string;
  constructor(private userService: UserService, private alertService: AlertService) {
  }
  ngOnInit() {
    this.userName = this.userService.userName;
    // 改变alertService的信息源
    this.alertService.success("初始化成功");
  }
}

app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  message: string;
  constructor(private alertService: AlertService) {
    //订阅alertServcie的message服务
     this.alertService.messageObserve.subscribe((res: any) => {
      this.message = res;
    });
  }
}

這樣訂閱者就能動態的跟著發布源變化

總結: 以上就是常用的通信方式,各種場景可以採取不同的方法

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

#

以上是對angular的元件通訊的解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript的角色:使網絡交互和動態JavaScript的角色:使網絡交互和動態Apr 24, 2025 am 12:12 AM

JavaScript是現代網站的核心,因為它增強了網頁的交互性和動態性。 1)它允許在不刷新頁面的情況下改變內容,2)通過DOMAPI操作網頁,3)支持複雜的交互效果如動畫和拖放,4)優化性能和最佳實踐提高用戶體驗。

C和JavaScript:連接解釋C和JavaScript:連接解釋Apr 23, 2025 am 12:07 AM

C 和JavaScript通過WebAssembly實現互操作性。 1)C 代碼編譯成WebAssembly模塊,引入到JavaScript環境中,增強計算能力。 2)在遊戲開發中,C 處理物理引擎和圖形渲染,JavaScript負責遊戲邏輯和用戶界面。

從網站到應用程序:JavaScript的不同應用從網站到應用程序:JavaScript的不同應用Apr 22, 2025 am 12:02 AM

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。

Python vs. JavaScript:比較用例和應用程序Python vs. JavaScript:比較用例和應用程序Apr 21, 2025 am 12:01 AM

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。

C/C在JavaScript口譯員和編譯器中的作用C/C在JavaScript口譯員和編譯器中的作用Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在行動中:現實世界中的示例和項目JavaScript在行動中:現實世界中的示例和項目Apr 19, 2025 am 12:13 AM

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

JavaScript和Web:核心功能和用例JavaScript和Web:核心功能和用例Apr 18, 2025 am 12:19 AM

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

了解JavaScript引擎:實施詳細信息了解JavaScript引擎:實施詳細信息Apr 17, 2025 am 12:05 AM

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境