我正在使用angular 2.我提供了一个服务,我想执行一个简单的任务,就像我在两个组件中创建服务对象一样。在component1将bool值更改为true时,我想使用该值,因为它在component2中。反之亦然。获取bool数据的更新值
我的服务是:
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 - >你忘了提,你必须提供JwtService在NgModule和删除供应商:JwtService]由两个组件。这样,每个组件就会有一个JwtService实例,而不是2个分离服务。 – mehul