美文网首页
angular 通过service共享数据

angular 通过service共享数据

作者: 咕嘟咕嘟li | 来源:发表于2019-08-21 14:04 被阅读0次

1.新建一个service文件

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

@Injectable({
  providedIn: 'root'
})
export class ControllService {
  // Observable boolean sources
  private showEditCountSource = new Subject<boolean>();
  // Observable boolean streams
  showEditCount$ = this.showEditCountSource.asObservable();
  // 通过调用该方法传值
  changeIsShowDetail(state: boolean) {
    this.showEditCountSource.next(state);
  }
}

2.在需要共享数据的组件中(比如A组件和B组件)引入ControllService
这里B组件是点击A组件元素后路由出来的模块

// A.component.ts
import { ControllService } from 'path';
import { Router, ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
...

@Component({
  ...
})
export class AComponent implements OnInit {
  ...
  isShowDetail = false;
  subscription: Subscription;
  constructor(
    ...
    public controllService: ControllService,
    public activatedRoute: ActivatedRoute) {
    // 通过监测路由query参数的变化来让A页面上的元素显示隐藏
    this.activatedRoute.queryParams.subscribe(params => {
      if (Object.keys(params).length === 0) {
        this.controllService.changeIsShowDetail(false);
      }
    });
    this.subscription = this.controllService.showEditCount$.subscribe(
      mission => {
        // 通过该参数显示隐藏该页面上的元素
        this.isShowDetail = mission;
      });
  }
  routeToB(id) {
    // 修改共享的数据
    this.controllService.changeIsShowDetail(true);
    // 必需添加queryParams,不然浏览器的返回无法监测到路由的变化
    this.router.navigate([`/b`],
      { queryParams: { type: id } });
  }
}

// B.component.ts
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { ControllService } from 'path';

@Component({
  ...
})
export class BComponent implements OnInit {
  constructor(
    public router: Router,
    public controllService: ControllService,
    public activatedRoute: ActivatedRoute) {
    // 刷新时也要隐藏掉A组件上的元素
    this.activatedRoute.queryParams.subscribe(params => {
      // 修改共享的数据
      this.controllService.changeIsShowDetail(true);
    });
  }

  ngOnInit() {
  }

}

相关文章

网友评论

      本文标题:angular 通过service共享数据

      本文链接:https://www.haomeiwen.com/subject/mbrbsctx.html