国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

angular中不同的組件間傳值與通信的方法

2019-11-19 14:59:39
字體:
來源:轉載
供稿:網友

本文主要介紹angular在不同的組件中如何進行傳值,如何通訊。主要分為父子組件和非父子組件部分。

父子組件間參數與通訊方法

使用事件通信(EventEmitter,@Output):

場景:可以在父子組件之間進行通信,一般使用在子組件傳遞消息給父組件;

步驟:

  1. 子組件創建事件EventEmitter對象,使用@output公開出去;
  2. 父組件監聽子組件@output出來的方法,然后處理事件。

代碼:

 // child 組件  @Component({   selector: 'app-child',   template: '',   styles: [``]  })  export class AppChildComponent implements OnInit {   @Output() onVoted: EventEmitter<any> = new EventEmitter();   ngOnInit(): void {    this.onVoted.emit(1);   }  }  // parent 組件  @Component({   selector: 'app-parent',   template: `    <app-child (onVoted)="onListen($event)"></app-child>   `,   styles: [``]  })  export class AppParentComponent implements OnInit {   ngOnInit(): void {    throw new Error('Method not implemented.');   }   onListen(data: any): void {    console.log('TAG' + '---------->>>' + data);   }  }

使用@ViewChild和@ViewChildren:

場景:一般用于父組件給子組件傳遞信息,或者父組件調用子組件的方法;

步驟:

  1. 父組件里面使用子組件;
  2. 父組件里面使用@ViewChild獲得子組件對象。
  3. 父組件使用子組件對象操控子組件;(傳遞信息或者調用方法)。

代碼:

// 子組件@Component({ selector: 'app-child', template: '', styles: [``]})export class AppChildComponent2 implements OnInit {  data = 1;  ngOnInit(): void { } getData(): void {  console.log('TAG' + '---------->>>' + 111); }}// 父組件@Component({ selector: 'app-parent2', template: `  <app-child></app-child> `, styles: [``]})export class AppParentComponent2 implements OnInit { @ViewChild(AppChildComponent2) child: AppChildComponent2; ngOnInit(): void {  this.child.getData(); // 父組件獲得子組件方法  console.log('TAG'+'---------->>>'+this.child.data);// 父組件獲得子組件屬性 }}

非父子組件參數傳遞與通訊方法

通過路由參數

場景:一個組件可以通過路由的方式跳轉到另一個組件 如:列表與編輯

步驟:

  1. A組件通過routerLink或router.navigate或router.navigateByUrl進行頁面跳轉到B組件
  2. B組件接受這些參數

此方法只適用于參數傳遞,組件間的參數一旦接收就不會變化

代碼

傳遞方式

routerLink

<a routerLink=["/exampledetail",id]></a>routerLink=["/exampledetail",{queryParams:object}]routerLink=["/exampledetail",{queryParams:'id':'1','name':'yxman'}];

router.navigate

this.router.navigate(['/exampledetail',id]);this.router.navigate(['/exampledetail'],{queryParams:{'name':'yxman'}});

router.navigateByUrl

this.router.navigateByUrl('/exampledetail/id');this.router.navigateByUrl('/exampledetail',{queryParams:{'name':'yxman'}});

傳參方傳參之后,接收方2種接收方式如下:

snapshot

import { ActivateRoute } from '@angular/router';public data: any;export class ExampledetailComponent implements OnInit {   constructor( public route: ActivateRoute ) { };  ngOnInit(){    this.data = this.route.snapshot.params['id'];  };}

queryParams

import { ActivateRoute } from '@angular/router';export class ExampledetailComponent implements OnInit {   public data: any;  constructor( public activeRoute:ActivateRoute ) { };  ngOnInit(){    this.activeRoute.queryParams.subscribe(params => {    this.data = params['name'];  });};

使用服務Service進行通信,即:兩個組件同時注入某個服務

場景:需要通信的兩個組件不是父子組件或者不是相鄰組件;當然,也可以是任意組件。

步驟:

  1. 新建一個服務,組件A和組件B同時注入該服務;
  2. 組件A從服務獲得數據,或者想服務傳輸數據
  3. 組件B從服務獲得數據,或者想服務傳輸數據。

代碼:

  // 組件A  @Component({   selector: 'app-a',   template: '',   styles: [``]  })  export class AppComponentA implements OnInit {   constructor(private message: MessageService) {   }   ngOnInit(): void {    // 組件A發送消息3    this.message.sendMessage(3);    const b = this.message.getMessage(); // 組件A接收消息;   }  }  // 組件B  @Component({   selector: 'app-b',   template: `    <app-a></app-a>   `,   styles: [``]  })  export class AppComponentB implements OnInit {   constructor(private message: MessageService) {   }   ngOnInit(): void {    // 組件B獲得消息    const a = this.message.getMessage();    this.message.sendMessage(5); // 組件B發送消息   }  }

消息服務模塊

場景:這里涉及到一個項目,里面需要實現的是所有組件之間都有可能通信,或者是一個組件需要給幾個組件通信,且不可通過路由進行傳參。

設計方式:

  1. 使用RxJs,定義一個服務模塊MessageService,所有的信息都注冊該服務;
  2. 需要發消息的地方,調用該服務的方法;
  3. 需要接受信息的地方使用,調用接受信息的方法,獲得一個Subscription對象,然后監聽信息;
  4. 當然,在每一個組件Destory的時候,需要
this.subscription.unsubscribe();

代碼:

  // 消息中專服務  @Injectable()  export class MessageService {   private subject = new Subject<any>();   /**   * content模塊里面進行信息傳輸,類似廣播   * @param type 發送的信息類型   *    1-你的信息   *    2-你的信息   *    3-你的信息   *    4-你的信息   *    5-你的信息   */   sendMessage(type: number) {    console.log('TAG' + '---------->>>' + type);    this.subject.next({type: type});   }   /**   * 清理消息   */   clearMessage() {    this.subject.next();   }   /**   * 獲得消息   * @returns {Observable<any>} 返回消息監聽   */   getMessage(): Observable<any> {    return this.subject.asObservable();   }  }  // 使用該服務的地方,需要注冊MessageService服務;  constructor(private message: MessageService) {  }  // 消息接受的地方;  public subscription: Subscription;  ngAfterViewInit(): void {    this.subscription = this.message.getMessage().subscribe(msg => {     // 根據msg,來處理你的業務邏輯。    })   }   // 組件生命周期結束的時候,記得注銷一下,不然會卡;   ngOnDestroy(): void {    this.subscription.unsubscribe();   }   // 調用該服務的方法,發送信息;   send():void {    this.message.sendMessage(‘我發消息了,你們接受下'); // 發送信息消息   }

這里的MessageService,就相當于使用廣播機制,在所有的組件之間傳遞信息;不管是數字,字符串,還是對象都是可以傳遞的,而且這里的傳播速度也是很快的。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 大理市| 石首市| 乌兰县| 浮梁县| 象州县| 年辖:市辖区| 离岛区| 荔浦县| 高青县| 梓潼县| 泾川县| 白河县| 兴化市| 炎陵县| 兖州市| 寻乌县| 仪征市| 偏关县| 九龙城区| 五台县| 邻水| 怀仁县| 武冈市| 托里县| 林州市| 武安市| 庐江县| 桂林市| 马尔康县| 通渭县| 武威市| 白银市| 商都县| 阿拉善右旗| 望谟县| 绥芬河市| 华阴市| 邳州市| 伊金霍洛旗| 博客| 太仓市|