angular设置全局变量,可修改监听变量

  1. 创建service.module.ts
import { NgModule, ModuleWithProviders } from '@angular/core';
import { SomeSharedService } from './global.service';
export {
  SomeSharedService
}

@NgModule()
export class ServicesModule { 
  static forRoot():ModuleWithProviders{
    return {
      ngModule:ServicesModule,
      providers:[SomeSharedService]
    }
  }
}
  1. 新建global.service.ts
import { Injectable } from '@angular/core'
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class SomeSharedService {
  public globalVar:BehaviorSubject<any[]> = new BehaviorSubject([]);
  public pageLimit = 10;
}
  1. 在header组件中引入服务并获取值
...
import { SomeSharedService } from 'src/app/services/global.service';
.....
  constructor(
    private someSharedService: SomeSharedService
  ) { 
  }

  ngOnInit() {
    this.someSharedService.globalVar.subscribe(d=>{
      this.clumb = d;
    })
  }
....
}
  1. 在task组件中引入服务并设置值

import { SomeSharedService } from 'src/app/services/global.service';
....
...
  constructor(
    private someSharedService$:SomeSharedService
  ) {}

 
  getProjectName(id:Number){
    this.someSharedService$.globalVar.next(['我的项目',{id:id,name:res.data.project_name}]
  }
....
}

这里设置了新的值,在header组件订阅 到改变后的值。

猜你喜欢

转载自www.cnblogs.com/hibiscus-ben/p/10407264.html