私はアングル2を使用しています。私はサービスを作ったので、私は2つのコンポーネントでサービスオブジェクトを作ったような簡単なタスクを実行したいと思います。ここでcomponent1はbool値をtrueに変更します。これはcomponent2の場合と同じ値を使用します。その逆も同じです。ブールデータの更新値を取得
私のサービスは次のとおりです。
import { Injectable } from '@angular/core';
@Injectable()
export class JwtService {
appStatus:boolean=false;
setStatus(value){
debugger;
this.appStatus = value;
}
getStatus(){
return this.appStatus;
}
}
マイ部品1時:
import { Component } from '@angular/core';
import { JwtService} from '../shared/services/jwt.service';
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [JwtService ]
})
export class AppComponent {
appStatus: boolean = false;
constructor(private jwtService:JwtService) { }
public Func() :any{
this.jwtService.setStatus(false);
}
}
マイコンポーネント2時:
import { Component, OnInit } from '@angular/core';
import { JwtService} from '../services/jwt.service'
@Component({
selector: 'layout-header',
templateUrl: './header.component.html',
providers: [JwtService]
})
export class HeaderComponent implements OnInit {
appStatus: boolean ;
constructor( private jwtservice:JwtService
) {
this.appStatus=jwtservice.getStatus();
}
setout()
{
this.jwtservice.setStatus(true);
}
}
ちょうどサービスで発表appstatusの変更された値を取得したいです。
@Haseoh - >あなたはNgModuleでJwtServiceを提供し、プロバイダを削除する必要があること、言及を忘れてしまった:[JwtService]の両方のコンポーネントから。このようにして、2つの個別サービスの代わりに、各コンポーネントの1つのJwtServiceインスタンスが存在します。 – mehul