首页 > 解决方案 > 无法使用角度订阅转移价值

问题描述

我正在使用主题和订阅在两个组件之间传输数据,但它对我不起作用。

// 第一个组件

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { SettingsHelperService } from '../settings-screen/settings-helper.service';

@Component({
  selector: 'app-master-data-config',
  templateUrl: './master-data-config.component.html',
  styleUrls: ['./master-data-config.component.css']
})
export class MasterDataConfigComponent implements OnInit, OnDestroy {

  zoneSelected: boolean = false;
  wingSelected: boolean = false;
  public subscription: Subscription;

  constructor(private settingHelperService: SettingsHelperService) { }

  public ngOnDestroy(): void {
    this.subscription.unsubscribe(); // onDestroy cancels the subscribe request
  }

  ngOnInit(): void {
    this.subscription = this.settingHelperService.getSelectedValue().subscribe(data => console.log(data));
  }

}

// 第二个组件

import { Component, OnInit } from '@angular/core';
import { SettingsHelperService } from './settings-helper.service';

@Component({
  selector: 'app-settings-screen',
  templateUrl: './settings-screen.component.html',
  styleUrls: ['./settings-screen.component.css']
})
export class SettingsScreenComponent implements OnInit {

  public UnitType = [
    {value: 'matric', viewValue: 'Matric'},
    {value: 'imperial', viewValue: 'Imperial'},
  ];

  zoneSelect: boolean = false;
  wingSelect: boolean = false;
  selectedUnitType: string;
  valueSelected = [];

  constructor(private settingHelperService: SettingsHelperService) { }

  ngOnInit() {
  }

  save(){
    let valueObj = {
      unitType: this.selectedUnitType,
      zoneSelect: this.zoneSelect,
      wingSelect: this.wingSelect
    }
    this.settingHelperService.setValues(valueObj);
  }

}

// 服务

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

@Injectable()
export class SettingsHelperService {

  public unitType:string;
  public valueSubmitted = null;

  public data = new Subject<any>();

  constructor() { }

  getSelectedValue(){
    return this.data.asObservable();
  }

  setValues(value){
    console.log(value);
    this.data.next(value);
  }

}

请建议我错在哪里..?

我没有检索组件中的更新值。

标签: angularrxjsobservable

解决方案


除了您没有在提供 SettingHelperService 的位置显示代码外,我没有看到您的代码有任何明显的问题。那可能是个问题。如果没有正确提供,两个组件都可以拥有自己的服务实例并且不共享同一个。尝试在服务中添加此代码:

@Injectable({
  providedIn: 'root',
})

如果那没有帮助,请检查我根据您的代码制作的 Stackblitz。添加上述内容后,它按原样工作:https ://angular-ivy-g8keel.stackblitz.io


推荐阅读