zoukankan      html  css  js  c++  java
  • angular2+ 组件间通信

    angular2+ 不同于react的redux,vue的vuex,angular2+其实可实现数据状态管理的方法很多,以下方案一般也足够支撑普通业务;

    父子组件通信

    1.1 父组件向子组件传递信息(@Input)

    • 父组件绑定信息
    <app-child childTitle="可设置子组件标题"></app-child>
    
    • 子组件接收消息
    import { Component, OnInit, Input } from '@angular/core';
    @Input childTitle: string;
    

    1.2 子组件向父组件传递信息


    • 子组件使用 EventEmitter 传递消息
    import { Component, OnInit, Output, EventEmitter } from '@angular/core';
    
    @Output() initEmit = new EventEmitter<string>();
    ngOnInit() {
      this.initEmit.emit("子组件初始化成功");
    }
    
    • 父组件接收消息
    <app-child (initEmit)="accept($event)"></app-child>
    accept(msg:string) {
      alert(msg);
    }
    

    使用 ViewChild

    // 父组件
    import { Component, ViewChild, AfterViewInit } from '@angular/core';
    
    @Component({
        selector: 'app-parent',
        template: `
        	Message: {{message}}
        	<app-child></app-child>
        `,
        styleUrls: ['./parent.component.css']
    })
    export class ParentComponent implements AfterViewInit {
        @ViewChild(ChildComponent) child;
        
        constructor() {}
        
        message: string;
        
        ngAfterViewInit() {
            this.message = this.child.message;
        }
    }
    
    
    // 子组件
    import { Component } from '@angular/core';
    
    @Component({
        
        message: string = 'Hola Mundo';
        
        constructor() {}
    })
    

    非父子组件通信

    • service服务
    // service.ts
    import { Component, Injectable, EventEmitter } from "@angular/core";
    @Injectable()
    export class myService {
      public info: string = "";
      constructor() {}
    }
    组件 1 向 service 传递信息
    import { myService } from '../../service/myService.service';
    ...
    constructor(
      public service: myService
    ) { }
    
    changeInfo() {
      this.service.info = this.service.info + "1234";
    }
    

    组件 2 从 service 获取信息

    import { myService } from '../../service/myService.service';
    
    constructor(
      public service: myService
    ) { }
    
    showInfo() {
      alert(this.service.info);
    }
    
    • 使用 BehaviorSubject

    优点:真正的发布订阅模式,当数据改变时,订阅者也能得到响应

    // service
    import { BehaviorSubject } from 'rxjs';
    public messageSource = new BehaviorSubject<string>('Start');
    changemessage(message: string): void {
      this.messageSource.next(message);
    }
    组件调用 service 的方法传信息和接收信息
    changeInfo() {
      this.communication.changemessage('Message from child 1.');
    }
    ngOnInit() {
      this.communication.messageSource.subscribe(Message => {
        window.alert(Message);
        this.info = Message;
      });
    }
    

    rxjs的observable

    1. 父组件:app.component.ts、app.component.html
    2. 子组件:home.component.html、home.component.html
    3. 服务:shared.service.ts
      关键方法
    4. Observable.subscribe() 用于订阅发送可观察对象的消息
    5. Subject.next() 用于向观察者对象发送消息,然后将其发送给改观察者的所有订阅者
    6. Subject.asObservable() 返回一个可观察对象,一旦值变化,便会同时向它的订阅者更新消息。

    shared.service公共服务

    //shared.service.ts
    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import { Subject } from 'rxjs/Subject';
    
    @Injectable()
    export class SharedService {
        private msg = new Subject<any>();
        //发送消息
        sendMessage(message: string) {
            this.msg.next(message);
        }
        //清除消息
        clearMessage() {
            this.msg.next();
        }
        //获取消息
        getMessage(): Observable<any> {
            return this.msg.asObservable();
        }
    }
    

    app父组件获取消息

    <!--app.component.html-->
    <p-growl [(value)]="alertMsg"></p-growl>
    //app.component.ts
    public alertMsg: Array<object>;
    constructor(private sharedService: SharedService) {}
    
    ngOnInit() {
        //消息提示 从service获取消息内容
        this.sharedService.getMessage().subscribe(value => {
            this.alertMsg = value;
        })
    
    }
    

    home子组件发送消息

    <!--home.component.html-->
    <button (click)="sendMessage()">Send Message</button>
    //home.component.ts
    constructor(private sharedService: SharedService) {}
    
    public sendMessage() {
            //发送消息
            this.sharedService.sendMessage('显示成功');
        }
    

    其他的通信方式

    1. 路由传值
    2. cookie、session、storage
  • 相关阅读:
    关于Windows版本的redis启动报错:Creating Server TCP listening socket 127.0.0.1:6379: bind: No error
    03 验证线程是数据共享的
    01 线程的两种创建方式
    33 线程的创建 验证线程之间数据共享 守护线程
    10 进程池的回调函数
    09 进程池的异步方法
    07 进程池的同步方法和异步方法
    08 进程池同步方法
    05 进程池map方法
    06 测试多进程的时间
  • 原文地址:https://www.cnblogs.com/mapleChain/p/12210859.html
Copyright © 2011-2022 走看看