【angualr4】 组件之间的通信

发布时间:2019-06-07 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了【angualr4】 组件之间的通信脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

父→子 input

parent.ts


import { component } From '@Angular/core';

@Component({
  selector: 'page-parent',
  templateUrl: 'parent.htML',
})
export class ParentPage {
  i: number = 0;
  constructor() {
    setInterval(() => {
      this.i++;
    }, 1000)
  }
}

parent.html

<ion-header>
  <ion-navbar>
    <ion-title>Parent</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Parent</h2>
  <page-child [content]="i"></page-child>
</ion-content>

child.ts

import { Component,Input } from '@angular/core';

@Component({
  selector: 'page-child',
  templateUrl: 'child.html',
})
export class ChildPage {
@Input() content:string;
  constructor() {
  }
}

child.html

<ion-content padding>
child:{{content}}
</ion-content>
 

【angualr4】 组件之间的通信

子→父 output

parent.ts

import { Component } from '@angular/core';

@Component({
  selector: 'page-parent',
  templateUrl: 'parent.html',
})
export class ParentPage {
  i: number = 0;

  numberIChange(i:number){
      this.i = i;
  }
}

parent.html

    <ion-header>
      <ion-navbar>
        <ion-title>Parent</ion-title>
      </ion-navbar>
    </ion-header>

<ion-content padding>
  <h2>Parent:{{i}}</h2>
  <page-child (changeNumber)="numberIChange($event)"></page-child>
</ion-content>

child.ts

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'page-child',
  templateUrl: 'child.html',
})

export class ChildPage {
  @Output() changeNumber: EventEmitter<number> = new EventEmitter();
  Number: number = 0;
  constructor() {
    setInterval(() => {
      this.changeNumber.emit(++this.Number);
    }, 1000)
  }
}

child.html

<ion-content padding>
     child
</ion-content>

【angualr4】 组件之间的通信

子获得父实例

parent.ts

import { Component } from '@angular/core';

@Component({
  selector: 'page-parent',
  templateUrl: 'parent.html',
})
export class ParentPage {
  i:number = 0;
}

parent.html

<ion-header>
  <ion-navbar>
    <ion-title>Parent</ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <h1>parent: {{i}}</h1>
  <page-child></page-child>
</ion-content>

child.ts

import { Component, Input, EventEmitter, Output,Host,Inject,forwardRef } from '@angular/core';
import{ParentPage} from '../parent/parent';
@Component({
  selector: 'page-child',
  templateUrl: 'child.html',
})
export class ChildPage {
    constructor( @Host() @Inject(forwardRef(() => ParentPage)) app: ParentPage) {
        setInterval(() => {
            app.i++;
        }, 1000);
    }
}

child.html

<ion-content padding>
 child 
</ion-content>

【angualr4】 组件之间的通信

父获得子实例

parent.ts

import {ViewChild, Component } from '@angular/core';
import{ChildPage}from '../child/child';

@Component({
  selector: 'page-parent',
  templateUrl: 'parent.html',
})
export class ParentPage {
  @ViewChild(ChildPage) child:ChildPage;
    ngAfterViewInit() {
        setInterval(()=> {
            this.child.i++;
        }, 1000)
    }
}

parent.html

<ion-header>
  <ion-navbar>
    <ion-title>Parent</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h1>parent {{i}}</h1>
  <page-child></page-child>
</ion-content>

child.ts

import { Component, Input, EventEmitter, Output,Host,Inject,forwardRef } from '@angular/core';


    @Component({
      selector: 'page-child',
      templateUrl: 'child.html',
    })
    export class ChildPage {
        i:number = 0;
    }

child.html

    <ion-content padding>
    <h2>child {{i}}</h2>
    </ion-content>
    
    

【angualr4】 组件之间的通信

service

parent.ts

import { Component } from '@angular/core';
import{myService}from '../child/myService'

@Component({
  selector: 'page-parent',
  templateUrl: 'parent.html',
})
export class ParentPage {
     i:number=0;
   constructor(service:myService) {
        setInterval(()=> {
            service.i++;
        }, 1000)
    }
}

parent.html

<ion-header>
  <ion-navbar>
    <ion-title>Parent</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
   <h1>parent {{i}}</h1>
   <page-child></page-child>
</ion-content>

child.ts

import { Component} from '@angular/core';
import{myService}from "../child/myService"
@Component({
  selector: 'page-child',
  templateUrl: 'child.html',
})
export class ChildPage {
    constructor(public service:myService){
    }
}

child.html

<ion-content padding>
<h2>child {{service.i}}</h2>
</ion-content>
myService.ts
ps:记得在app.module.ts 加上providers: [KmyService]
import{Injectable } from '@angular/core';
@Injectable()
export class KmyService {
    i:number = 0;
}

EventEmitter

myService.ts

import {Component,Injectable,EventEmitter} from '@angular/core';
@Injectable()
export class myService {
    change: EventEmitter<number>;

    constructor(){
        this.change = new EventEmitter();
    }
}

parent.ts

import { Component } from '@angular/core';
import{myService}from '../child/myService'

@Component({
  selector: 'page-parent',
  templateUrl: 'parent.html',
})
export class ParentPage {
    i:number = 0;
    constructor(service:myService) {
        setInterval(()=> {
            service.change.emit(++this.i);
        }, 1000)
    }
}

parent.html

<ion-header>
  <ion-navbar>
    <ion-title>Parent</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
   <h1>parent {{i}}</h1>
   <page-child></page-child>
</ion-content>

child.ts

import { Component,  EventEmitter} from '@angular/core';

import{myService}from "../child/myService"
@Component({
  selector: 'page-child',
  templateUrl: 'child.html',
})
export class ChildPage {

    i:number = 0;

    constructor(public service:myService){
        service.change.subscribe((value:number)=>{
            this.i = value;
        })
    }
    
}

child.html

<ion-content padding>
 <h2>child {{i}}</h2>
</ion-content>

# 订阅

message.service.ts

import { Injectable } from '@angular/core';
import {Subject, Observable} from 'rxjs/';

@Injectable()
export class MessageService {

  constructor() { }
  private subject = new Subject<any>();

  sendMessage(something: any) {
    this.subject.next(something);
  }

  clearMessage() {
    this.subject.next();
  }

  getMessage(): Observable<any> {
    return this.subject.asObservable();
  }
}

子组件

home.COMponent.ts

import {Component, EventEmitter, OnInit, Output} from                             '@angular/core';
    import {MessageService} from '../message.service';
    
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.css']
    })
    export class HomeComponent implements OnInit {
      message: any;
    
      constructor(private messageService: MessageService) {
      }
    
      ngOnInit() {
      }
    
      sendMessage(): void { // 发送消息
        this.message = 'subject';
        this.messageService.sendMessage(this.message);
      }
    
      clearMessage(): void { // 清除消息
        this.messageService.clearMessage();
      }
    
    }

home.component.html

<input type="button" value="Subject" (click)="sendMessage()">
<input type="button" value="clear" (click)="clearMessage()">
父组件
app.component.ts

import {Component, OnInit} from '@angular/core';
import {MessageService} from './message.service';
import {Subscription} from 'rxjs/Subscription';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  message: any;
  subscription: Subscription;
  constructor(private messageService: MessageService) {
  }

  ngOnInit(): void {
    this.subscription = this.messageService.getMessage()
      .subscribe(message => { this.message = message; });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

app.component.html

<app-home></app-home>
<div>{{message | json}}</div>

非父子

非父子组件见通信可以通过同一个service来实现。需要注意的是一定要在service中定义一个临时变量来供传递。比如我有两个组件来传递一个Book类型的数据,HomeComponent -> BookComponent,Book和service定义如下:

import {EventEmitter, Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
export class Book {
  name: string;
  price: number;
}

@Injectable()
export class BookService {
  defaultBook: Book = {name: '《额尔古纳河右岸》', price: 20};
  bookEventer: EventEmitter<Book> = new EventEmitter();
}

主页组件HomeComponent,它用来提供数据,定义如下:

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit, OnDestroy {
  book: Book;

  constructor(private bookService: BookService) {
  }

  ngOnInit() {
    this.book = {name: '《万历十五年》', price: 10.0};
  }

  ngOnDestroy() {
    this.bookService.bookEventer.emit(this.book);
  }
}

书籍组件BookComponent,用来接收数据,定义如下:

import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {Book, BookService} from './book';

@Component({
  selector: 'app-book',
  templateUrl: './book.component.html',
  styleUrls: ['./book.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class BookComponent implements OnInit {
  protected subscribeBook: Book;

  constructor(private bookService: BookService) {
    bookService.bookEventer.subscribe(book => {
    bookService.defaultBook = book;
    });
  }

  ngOnInit() {
    this.subscribeBook = this.bookService.defaultBook;
  }
}

书籍组件模板文件定义如下:

<p>
  subscribeBook:{{subscribeBook | json}}
</p>



订阅

message.service.ts

import { Injectable } from '@angular/core';
import {Subject, Observable} from 'rxjs/';

@Injectable()
export class MessageService {

  constructor() { }
  private subject = new Subject<any>();

  sendMessage(something: any) {
    this.subject.next(something);
  }

  clearMessage() {
    this.subject.next();
  }

  getMessage(): Observable<any> {
    return this.subject.asObservable();
  }
}

子组件

home.component.ts

import {Component, EventEmitter, OnInit, Output} from                             '@angular/core';
    import {MessageService} from '../message.service';
    
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.css']
    })
    export class HomeComponent implements OnInit {
      message: any;
    
      constructor(private messageService: MessageService) {
      }
    
      ngOnInit() {
      }
    
      sendMessage(): void { // 发送消息
        this.message = 'subject';
        this.messageService.sendMessage(this.message);
      }
    
      clearMessage(): void { // 清除消息
        this.messageService.clearMessage();
      }
    
    }

home.component.html

<input type="button" value="Subject" (click)="sendMessage()">
<input type="button" value="clear" (click)="clearMessage()">

父组件

app.component.ts

import {Component, OnInit} from '@angular/core';
import {MessageService} from './message.service';
import {Subscription} from 'rxjs/Subscription';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  message: any;
  subscription: Subscription;
  constructor(private messageService: MessageService) {
  }

  ngOnInit(): void {
    this.subscription = this.messageService.getMessage()
      .subscribe(message => { this.message = message; });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

app.component.html

<app-home></app-home>
<div>{{message | json}}</div>

非父子

非父子组件见通信可以通过同一个service来实现。需要注意的是一定要在service中定义一个临时变量来供传递。比如我有两个组件来传递一个Book类型的数据,HomeComponent -> BookComponent,Book和service定义如下:

import {EventEmitter, Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
export class Book {
  name: string;
  price: number;
}

@Injectable()
export class BookService {
  defaultBook: Book = {name: '《额尔古纳河右岸》', price: 20};
  bookEventer: EventEmitter<Book> = new EventEmitter();
}

主页组件HomeComponent,它用来提供数据源,定义如下:

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit, OnDestroy {
  book: Book;

  constructor(private bookService: BookService) {
  }

  ngOnInit() {
    this.book = {name: '《万历十五年》', price: 10.0};
  }

  ngOnDestroy() {
    this.bookService.bookEventer.emit(this.book);
  }
}

书籍组件BookComponent,用来接收数据,定义如下:

import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {Book, BookService} from './book';

@Component({
  selector: 'app-book',
  templateUrl: './book.component.html',
  styleUrls: ['./book.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class BookComponent implements OnInit {
  protected subscribeBook: Book;

  constructor(private bookService: BookService) {
    bookService.bookEventer.subscribe(book => {
    bookService.defaultBook = book;
    });
  }

  ngOnInit() {
    this.subscribeBook = this.bookService.defaultBook;
  }
}

书籍组件模板文件定义如下:

<p>
  subscribeBook:{{subscribeBook | json}}
</p>

脚本宝典总结

以上是脚本宝典为你收集整理的【angualr4】 组件之间的通信全部内容,希望文章能够帮你解决【angualr4】 组件之间的通信所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。