zoukankan      html  css  js  c++  java
  • angular设置全局变量,修改监听变量

    创建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]
        }
      }
    }

    新建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中引入服务并获取值

    ...
    import { SomeSharedService } from 'src/app/services/global.service';
    .....
      constructor(
        private someSharedService: SomeSharedService
      ) { 
      }
    
      ngOnInit() {
        this.someSharedService.globalVar.subscribe(d=>{
          this.clumb = d;
        })
      }
    ....
    }

    在组件2中引入服务并设置值

    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}]
      }
    ....
    }

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

  • 相关阅读:
    使用telnet模拟http请求
    07_Python变量内存地址、小数据池
    04_Linux命令
    03_Linux文件和目录
    06_Python Encoded
    05_Python Format Operation
    04_Python Data Structures
    02_Python基本数据类型
    01_软件开发流程
    03_线性表应用一:栈
  • 原文地址:https://www.cnblogs.com/mary-123/p/11206694.html
Copyright © 2011-2022 走看看