zoukankan      html  css  js  c++  java
  • angular在服务中调用组件的某个方法,并传参给组件,(反向调用),变量改变后,强制更新视图

    需要被调用方法的组件文件

    
    
    import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
    import { SettingsService } from '@delon/theme';
    import { SetdataService } from './setdata.service'
    import { NgZone } from '@angular/core';

    @Component({
    selector: 'layout-header',
    templateUrl: './header.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
    })
    export class HeaderComponent {
    searchToggleStatus: boolean;

    constructor(
    public settings: SettingsService,
    // 組件頁面需要添加的代碼1
    private testservice: SetdataService,
    private zone: NgZone,
    private cdf: ChangeDetectorRef
    // 組件頁面需要添加的代碼2
    ) {
    // 組件頁面需要添加的代碼1
    this.testservice.testComponent$.subscribe(res => {
    console.log(res) //這是接收到的參數
    this.zone.run(() => {
    this.test(res)
    this.cdf.markForCheck(); // 进行标注
    this.cdf.detectChanges(); // 要多加一行这个 执行一次变化检测
    })
    })
    // 組件頁面需要添加的代碼2
    }
    myData = '000'

    toggleCollapsedSidebar() {
    this.settings.setLayout('collapsed', !this.settings.layout.collapsed);
    }

    searchToggleChange() {
    this.searchToggleStatus = !this.searchToggleStatus;
    }

    // 組件頁面需要添加的代碼1
    test(a) {
    this.myData = a //第二个组件通过服务调用这个方法,并且传参过来改变页面
    }
    // 組件頁面需要添加的代碼2
    }
     

    创建一个服务,添加如下代码

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

    @Injectable({
    providedIn: 'root'
    })

    export class SetdataService {
    constructor(
    ) { }
    messageSubject = new Subject();
    private testComponentSource = new Subject<boolean>();
    testComponent$ = this.testComponentSource.asObservable();
    // 这个就是方法可以调用传参给第一个组件
    dummy(a) {
    this.testComponentSource.next(a);
    }
    }
     

    我们在另一个组件里调用这个服务的方法,就会连锁调用上个组件的那个方法~~

    import { SetdataService } from '../../../layout/default/header/setdata.service'
    
    export class UploadImgComponent implements OnInit {
    
     
      constructor(
        private ser: SetdataService
      ) { }
    setData() {
        this.ser.dummy('haha')
      }

  • 相关阅读:
    tomcat 服务器的几个重要监听 方法 与 使用
    webSocket 前端 js 加入 心跳机制 的基本写法
    Palinwords (处理回文串)
    Anti-Rhyme Pairs (求最长公共前缀)
    Extend to Palindrome (顺序Hash和逆序Hash处理回文)
    Milk Patterns (hash + 二分)
    次小生成树
    Borg Maze (BFS预处理+最小生成树)
    P1126 机器人搬重物
    P1141 01迷宫 (记忆化搜索)
  • 原文地址:https://www.cnblogs.com/sugartang/p/12605162.html
Copyright © 2011-2022 走看看