【问题标题】:Template not updating when using Service Store (BehaviorSubject) to communicate between component使用 Service Store (BehaviorSubject) 在组件之间进行通信时模板未更新
【发布时间】:2020-06-03 13:29:00
【问题描述】:

我正在使用服务商店在两个非亲属组件之间进行通信。订阅服务变量 teste 的组件正在获取当前值,但它仅在第一次更新其模板

这是调试时的图像。你能看到吗,变量有值,但它不更新模板。

LoggedInstanceStore

import { Injectable } from '@angular/core';
import { Instance } from 'src/app/features/cadastros/instancia/instancia.component';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class LoggedInstanceStore {
    private _loggedInstance: Instance = null

    public trackerLoggedInstance = new BehaviorSubject<any>(this._loggedInstance);

    public teste = this.trackerLoggedInstance.asObservable();

    getLoggedInstanceValue() {
        return this.teste
    }

    setLoggedInstanceValue(loggedInstance: Instance) {
        this.trackerLoggedInstance.next(loggedInstance)
    }

    resetLoggedInstanceValue(): void {
        this.trackerLoggedInstance.next(this._loggedInstance);
    }
}

InstanceLoginComponent 的登录方法。在这里我第一次设置值

 login() {    
    let instanceLogin = this.instanceLoginForm.getRawValue()
    this.storage.setInstanceLogin(instanceLogin.instanceId)

    this.loggedInstanceStore.setLoggedInstanceValue(instanceLogin.instanceId)
    this.route.navigate(['app/cadastro/sistema'])
  }

这是我遇到问题的组件

import { Component, OnInit, Input, OnChanges, NgZone, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { Instance } from 'src/app/features/cadastros/instancia/instancia.component';
import { TranslateService } from '@ngx-translate/core';
import { LoggedInstanceStore } from './logged-instance.store';

@Component({
  selector: 'app-logged-instance',
  templateUrl: './logged-instance.component.html',
  styleUrls: ['./logged-instance.component.scss'],
})
export class LoggedInstanceComponent implements OnInit{

  loggedInstance: Instance;


  constructor(
    private loggedInstanceStore: LoggedInstanceStore,
    private translate: TranslateService,
    private ngZone: NgZone,
    private ref: ChangeDetectorRef
  ) {
    // const browserLang = translate.getBrowserLang();
    const browserLang = localStorage.getItem('appLanguage')
    translate.use(browserLang.match(/en|pt/) ? browserLang : 'en');

  }

  ngOnInit() {
    this.loggedInstanceStore.teste
    .subscribe(data => {
        if(data){
          this.loggedInstance = data
          this.ref.detectChanges()
        }        
      })
  }

}

这也是改变 LoggedStore 的 teste 变量值的组件

import { Component, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Instance } from '../../cadastros/instancia/instancia.component';
import { ActivatedRoute } from '@angular/router';
import { StorageService } from 'src/app/core/storage/storage.service';
import { LoggedInstanceStore } from 'src/app/components/header/logged-instance/logged-instance.store';
import { UtilsService } from 'src/app/services/utils/utils.service';
import { LoaderService } from 'src/app/components/loader/loader.service';
import Swal from 'sweetalert2';

const Toast = Swal.mixin({
  toast: true,
  position: 'top-end',
  timer: 6000,
  customClass: {
    confirmButton: 'btn btn-sm btn-success ',
  },
  animation: false
})

@Component({
  selector: 'app-change-instance',
  templateUrl: './change-instance.component.html',
  styleUrls: ['./change-instance.component.scss']
})
export class ChangeInstanceComponent implements OnInit, OnChanges {
  instances: Instance[] = []
  changeInstanceForm: FormGroup
  constructor(
    private fb: FormBuilder,
    private activatedRoute: ActivatedRoute,
    private storageService: StorageService,
    private loggedInstanceStore: LoggedInstanceStore,
    private utilsService: UtilsService,
    private loaderService: LoaderService
  ) { }

  ngOnChanges(changes: SimpleChanges): void {

  }

  ngOnInit() {
    this.instances = this.activatedRoute.snapshot.data['instances'];

    this.changeInstanceForm = this.fb.group({
      instance: ['']
    })
  }



  alterar() {
    debugger
    this.loaderService.show()
    let instanceSelected: Instance = this.changeInstanceForm.getRawValue();
    this.storageService.setInstanceLogin(instanceSelected)
    this.loggedInstanceStore.setLoggedInstanceValue(instanceSelected)
    this.utilsService.showAlertRequestSuccess

    this.loaderService.hide()

    Toast.fire(`Alteração efetuado com sucesso`, '', 'success')

    this.changeInstanceForm.reset()
  }

}

【问题讨论】:

    标签: angular rxjs observable behaviorsubject


    【解决方案1】:

    我发现我哪里出错了。 ChangeInstanceComponent 有一个表单,其中只有一个名为“instance”的 formControl。在方法 alterar() 中,我使用 this.changeInstanceForm.getRawValue() 获取表单的值,然后它返回了具有此结构的对象

    {
      "instance": {
        "Id": "10",
        "Name": "CBR",
        "ChannelId": 46,
        "ChannelName": "Confluence"
      }
    }
    

    这就是问题所在。因为 LoggedInstanceComponent 需要一个具有这种结构的对象

    {
      "Id": "8",
      "Name": "ABC Pneus",
      "ChannelId": 43,
      "ChannelName": "Intragroup"
    }
    

    我只是改变了像这样获取表单值的方式

    changeInstanceForm.get('instance').value;
    

    【讨论】:

      猜你喜欢
      • 2019-06-23
      • 2018-01-10
      • 1970-01-01
      • 2021-11-07
      • 2019-05-26
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      相关资源
      最近更新 更多