首頁 > web前端 > js教程 > 主體

angular組件間傳值與通訊使用詳解

php中世界最好的语言
發布: 2018-04-16 10:22:06
原創
1685 人瀏覽過

這次帶給大家angular組件間傳值與通信使用詳解,angular組件間傳值與通信的注意事項有哪些,下面就是實戰案例,一起來看一下。

本文主要介紹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的時候,需要
  5. #
    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,就等於使用廣播機制,在所有的元件之間傳遞訊息;不管是數字,

字串,還是物件都是可以傳遞的,而且這裡的傳播速度也是很快的。 

我相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

js封裝操作class步奏詳解

標籤selected="selected"屬性失效如何處理

以上是angular組件間傳值與通訊使用詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!