【发布时间】:2017-11-25 08:05:42
【问题描述】:
我正在尝试将变量从一个组件传递到另一个组件。我通过使用服务来做到这一点:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class SharedService {
// private questionNumber = new Subject<number>();
// questionNumber$ = this.questionNumber.asObservable();
questionNumber : number;
publishData(number:number) {
this.questionNumber = number;
console.log(this.questionNumber,'publish');
}
getQuestionData(){
console.log(this.questionNumber,'get');
return this.questionNumber;
}
constructor() { }
}
如果数据在函数“publishData”中发生变化,它会在控制台中写入当前变量值:
但如果我尝试访问该变量,它仍然是未定义的,就好像它没有被改变一样
组件 1(摘录):
import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { SharedService } from '../shared.service';
@Component({
selector: 'app-main-quiz',
templateUrl: './main-quiz.component.html',
styleUrls: ['./main-quiz.component.css'],
encapsulation: ViewEncapsulation.None,
providers: [SharedService]
})
export class MainQuizComponent implements OnInit {
constructor(private _sharedService: SharedService){
this._sharedService = _sharedService;
}
updateQuestion(){
this._sharedService.publishData(this.questionNumber);
};
组件 2:
import { Component, OnInit, Input } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { SharedService } from '../shared.service';
@Component({
selector: 'app-win-page',
templateUrl: './win-page.component.html',
styleUrls: ['./win-page.component.css'],
encapsulation: ViewEncapsulation.None,
inputs: ['questionNumber'],
providers: [SharedService]
})
export class WinPageComponent implements OnInit {
constructor(private _sharedService : SharedService) {
this._sharedService = _sharedService;
this.questionNumber = this._sharedService.getQuestionData();
}
questionNumber : number;
ngOnInit() {
}
ngOnChanges(){
this.questionNumber = this._sharedService.getQuestionData();
}
}
为什么那个变量没有更新?
感谢您的帮助!
【问题讨论】:
-
你怎么称呼它?也许您在设置变量之前就获得了它?
-
在我的第二个组件中:ngOnChanges(){ this.questionNumber = this._sharedService.getQuestionData(); }
-
可以分享组件代码吗? (带有
@Component注释) -
你在哪里设置的?
标签: angular variables typescript scope