Ich versuche, eine Variable von einer Komponente zu einer anderen zu übergeben. Ich tue, dass ein Dienst mithilfe:Dienstvariable beim Übergeben von Daten von einer Komponente an eine andere Winkel 2
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() { }
}
Wenn die Daten in der Funktion „publishData“ geändert wird es den aktuellen Variablenwert in der Konsole schreibt:
Aber wenn ich versuche, für den Zugriff auf diese Variable nicht definiert es noch so ist, wenn es
nicht geändert wirdKomponente 1 (e Xcerpt):
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);
};
Komponente 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();
}
}
Warum nicht diese Variable aktualisiert?
Danke für Ihre Hilfe!
wie nennst du es? Vielleicht bekommst du die Variable, bevor sie gesetzt wird? –
In meiner zweiten Komponente: ngOnChanges() { this.questionNumber = this._sharedService.getQuestionData(); } – Snixells
Können Sie die Komponentencodes teilen? (mit ihrer '@ Component' Annotation) – echonax