首頁  >  文章  >  web前端  >  angular中不同元件間傳值與通訊方法分享

angular中不同元件間傳值與通訊方法分享

小云云
小云云原創
2018-01-19 14:43:021523瀏覽

本文主要介紹了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: &#39;app-parent&#39;,
   template: `
    <app-child (onVoted)="onListen($event)"></app-child>
   `,
   styles: [``]
  })
  export class AppParentComponent implements OnInit {
   ngOnInit(): void {
    throw new Error(&#39;Method not implemented.&#39;);
   }
   onListen(data: any): void {
    console.log(&#39;TAG&#39; + &#39;---------->>>&#39; + data);
   }
  }

使用@ViewChild和@ViewChildren:

## 場景:一般用於父元件給子元件傳遞訊息,或是父元件呼叫子元件的方法;

步驟:

  1. 父元件裡面使用子元件;

  2. 父元件裡面使用@ViewChild取得子元件物件。

  3. 父元件使用子元件物件操控子元件;(傳遞訊息或呼叫方法)。

程式碼:


// 子组件
@Component({
 selector: &#39;app-child&#39;,
 template: &#39;&#39;,
 styles: [``]
})
export class AppChildComponent2 implements OnInit {
  data = 1;
  ngOnInit(): void {
 }
 getData(): void {
  console.log(&#39;TAG&#39; + &#39;---------->>>&#39; + 111);
 }
}
// 父组件
@Component({
 selector: &#39;app-parent2&#39;,
 template: `
  <app-child></app-child>
 `,
 styles: [``]
})
export class AppParentComponent2 implements OnInit {
 @ViewChild(AppChildComponent2) child: AppChildComponent2;
 ngOnInit(): void {
  this.child.getData(); // 父组件获得子组件方法
  console.log(&#39;TAG&#39;+&#39;---------->>>&#39;+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:&#39;id&#39;:&#39;1&#39;,&#39;name&#39;:&#39;yxman&#39;}];

router.navigate


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

router.navigateByUrl


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

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

snapshot


#

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

queryParams


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

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

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

步驟:

  1. 新建一個服務,元件A和元件B同時注入該服務;

  2. 元件A從服務取得數據,或想服務傳輸資料

  3. 元件B從服務取得數據,或是想服務傳輸資料。

程式碼:


  // 组件A
  @Component({
   selector: &#39;app-a&#39;,
   template: &#39;&#39;,
   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: &#39;app-b&#39;,
   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发送消息
   }
  }

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

設計方式:

    使用RxJs,定義一個服務模組MessageService,所有的資訊都註冊該服務;
  1. 需要發送訊息的地方,呼叫該服務的方法;
  2. 需要接受訊息的地方使用,呼叫接受訊息的方法,取得一個Subscription對象,然後監聽訊息;
  3. 當然,在每一個元件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(&#39;TAG&#39; + &#39;---------->>>&#39; + 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(‘我发消息了,你们接受下&#39;); // 发送信息消息
   }

這裡的MessageService,就相當於使用廣播機制,在所有的元件之間傳遞訊息;不管是數字,字串,還是物件都是可以傳遞的,而且這裡的傳播速度也是很快的。


相關推薦:


vue中頁面反傳值簡單實作方法分享

實作PHP中session和cookie資料傳值功能

php中傳值的方法介紹

#

以上是angular中不同元件間傳值與通訊方法分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn