如何在导入的组件的函数中使变量反映其当前值,而不是在angular8中反映其初始值?

时间:2019-06-14 11:27:08

标签: angular typescript

我在另一个组件的构造函数中为导入的组件声明了一个私有变量。例子

constructor( private x: Xcomponent){} 

然后我调用Xcomponent内部声明的函数

 x.scanx()

在scanx函数内部有一个变量,其初始值为ShouldChange=null;,在调用scanx之前,它的值已由Xcomponent内部的另一个函数更改为ShouldChange ={ 'some':'something'} ;,现在,当从另一个组件中调用scanx时,其值ShouldChange为null。我尝试访问在类(不是组件)中声明和更改的变量的值,并且在尝试访问导入的组件的值时,得到的不是当前值,而是初始值。

我正在使用可视代码IDE。语言是打字稿。

import { Xcomponent } from '../Xcomponent/xcomponent.component';
import { Globals } from '../globals';

export class parentComponent implements OnInit {
    constructor(private x: Xcomponent, private global: Globals) {
    }

    runThisFunction() {
        x.scanx(global.theVariableRetainsEditedValue); // The variable in global instance retains the changed values.
    }
}

// Inside scanx function of Xcomponent
export class Xcomponent implements OnInit {
    ShouldChange = null;

    someotherFunction() {
        this.ShouldChange = {'some': 'somethingelse'}
    }

    ngOnInit() {
this.someotherFunction();
this.confirmTheChange();
    }

    confirmTheChange() {
        if (this.ShouldChange === null) {
            alert("This never happens");
        }
        else {
            alert("THE VALUE WAS INDEED CHANGED");
        }
    }

    scanx(SomeInput) {
        if (this.ShouldChange === null) {
            alert("This Should not happen");
        } else {
            alert("This is not happening. Why?");
        }
    }
}

我希望变量ShouldChange的值不为null,因为它在ngOninit中已更改。但是,当从组件的导入实例调用时,它反映了其初始值。但是,从未导入的组件实例中检查变量的值表明,该值确实发生了更改,如confirmTheChange()函数所示。

2 个答案:

答案 0 :(得分:0)

问题可能是您未获得新值,因为该函数未返回新值...

在更改y值的函数上,添加一个 return y结尾为

scanx(){
*// the rest of the function that changed the code*
return y
}

,以及您要呼叫'scanx'

的其他组件上
runThisFunction() {
 const y = x.scanx(global.theVariableRetainsEditedValue); // The variable in global instance retains the changed values.
*y will hold the new value*
}

如果这不起作用,则使用可观察对象将是一个很好的解决方案。 您在服务中创建一个可观察对象,它将充当两者之间的数据中介者 RxJS BehaviorSubject是一个不错的选择。

第一步 -创建一个新服务并创建一个BehaviorSubject并创建一个用于更改可观察值的方法

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

@Injectable()
export class ValueChangerService {
  private initialValue = new BehaviorSubject(0);
  currentValue = this.initialValue.asObservable();

  constructor() { }

  changeValue(value: number) {
    this.initialValue.next(value)
  }
}

第二步 将服务注入您的组件并更改一个组件中的值

import { Component, OnInit } from '@angular/core';
import { ValueChangerService } from './value-changer.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private valueChanger: ValueChangerService) {
  }


  setValue(value) {
    this.valueChanger.changeValue(value);
  }
}

第三步 在其他组件中订阅它

import { Component, OnInit } from '@angular/core';
import { ValueChangerService } from "./value-changer.service";

@Component({
  selector: 'hello',
  template: `
   Hello Component
   the value of y is {{y}}
  `,
  styleUrls: ['./app.component.css']
})
export class HelloComponent implements OnInit {

  y: number;

  constructor(private valueChanger: ValueChangerService) { }
  ngOnInit() {
    this.valueChanger.currentValue.subscribe(value => this.y = value)
  }
}

您可以在https://stackblitz.com/edit/angular-gvh6xj

中找到完整的代码

然后查看Jeff Delaney的https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/

答案 1 :(得分:0)

Working example

  

X组件

 import { Component, OnInit } from '@angular/core';
    import {TestService} from "./test.service"

    @Component( {
      selector: 'x-child',
      template: ``,
    })
    export class XchildComponent implements OnInit {

      constructor(private valueChanger: TestService) { 

         this.valueChanger.currentValue.subscribe(value =>  
         this.ShouldChange = value
            )
      }

      ShouldChange = null;

        someotherFunction() {
          //  this.ShouldChange = {'some': 'somethingelse'}

             this.valueChanger.changeValue({'some': 'somethingelse'});
        }

        ngOnInit() {

          this.someotherFunction();
          this.confirmTheChange();
        }

        confirmTheChange() {
            if (this.ShouldChange === null) {
                alert("This never happens");
            }
            else {
                alert("THE VALUE WAS INDEED CHANGED");
            }
        }

        scanx(value: any) {
            if (this.ShouldChange === null) {
                alert("This Should not happen");
            } else {
                alert("This is not happening. Why?");
            }
        }
    }
  

父项

import { XchildComponent } from './x-child.component'
import { Component , ViewChild, AfterViewInit} from "@angular/core";

@Component( {
  selector: 'parent',
  template: ``,

})
export class ParentComponent implements AfterViewInit {
constructor(public child: XchildComponent) {

}


ngAfterViewInit() {

this.child.scanx('checking new value')
}


}
  

希望,这可以解决您的问题