저는 Angular 5 싱글 톤 서비스를하고 있습니다. 내 의견으로는 가이드 라인에 따라 모든 것을했지만, 불행히도 내 서비스는 싱글 톤이 아닙니다. 각 구성 요소에는 서비스 인스턴스가있는 것 같습니다. 내 코드는 다음과 같습니다Angular 5 Service as singleton
응용 프로그램 모듈 :
import { StarService } from './star-service/star-service'
import { StarSearchComponent } from './star-search/star-search.component'
import { StarReportComponent } from './star-report/star-report.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
AppRoutingModule
],
declarations: [
AppComponent,
StarSearchComponent,
StarReportComponent
],
providers: [StarService
],
bootstrap: [AppComponent]
})
export class AppModule {
}
서비스 :
import { Injectable } from '@angular/core';
import { log } from 'util';
@Injectable()
export class StarService {
public Param: string;
constructor() {
this.Param = "Not Set";
console.log("Service Instance created");
}
}
별 보고서 구성 요소
import { Component, OnInit } from '@angular/core';
import { StarService } from '../star-service/star-service'
@Component({
selector: 'app-star-report',
templateUrl: '<p>{{getReport}}</p>',
styleUrls: ['./star-report.component.css']
})
export class StarReportComponent implements OnInit {
constructor(private starService: StarService) { }
ngOnInit() {
this.starService.Param = "Report";
}
get getReport(): string
{
return this.starService.Param;
}
}
별 검색 구성 요소
import { Component, OnInit } from '@angular/core';
import { StarService } from '../star-service/star-service'
@Component({
selector: 'app-star-search',
templateUrl: './star-search.component.html',
styleUrls: ['./star-search.component.css']
})
export class StarSearchComponent implements OnInit {
constructor(private starService: StarService) { }
ngOnInit() {
}
get getSearch(): string
{
return this.starService.Param;
}
}
그리고 지금, 내 콘솔을 표시 할 때마다 나는 요소를 전환하고있어 "서비스 인스턴스 생성". 또한 각 구성 요소는 잘못된 텍스트를 표시합니다. 필자는 StarReportComponent가 생성 될 때 starService.Param = "Report"를 전환하고 그대로 유지합니다. 불행하게도 StarSearchComponent를 호출하면 기본값 "Not Set"가 표시됩니다. 왜? 왜 싱글 톤이 여기서 작동하지 않습니까? 감사합니다.
예제 코드를 사용하여이 코드를 재현 할 수 없습니다. https://stackblitz.com/edit/angular-mwxab5?file=app%2Fapp.component.ts –
감사합니다. 동일한 구성 요소 시간 : app-star-report> app-star-search> 나는 라우팅을 통해 그들 사이를 오히려 전환 할 것입니다. 어떤 차이가 있습니까? –
Shark