【问题标题】:Service variable when passing data from one component to another angular 2将数据从一个组件传递到另一个 Angular 2 时的服务变量
【发布时间】: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


【解决方案1】:

这里已经回答了:Angular - shared service between components doesn't work

每个组件都有:

providers: [SharedService]

因此,基于角度DI Hierachy,该服务将仅适用于当前组件。 在您的情况下,这意味着每个组件都有自己的实例 (service isolation)。

如果您希望您的组件共享同一个实例,您需要在模块级别声明提供程序。

【讨论】:

    猜你喜欢
    • 2017-11-29
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2018-02-22
    相关资源
    最近更新 更多