Angular 在typescript中获取set变量
我正在使用angular2和typescript。在其中一个服务中,我设置并获取如下变量的值:Angular 在typescript中获取set变量,angular,typescript,Angular,Typescript,我正在使用angular2和typescript。在其中一个服务中,我设置并获取如下变量的值: import {Injectable} from '@angular/core'; @Injectable() export class UserProfileService { isLoggedIn: boolean; constructor() { } setLoggedInStatus(status) { console.log('stat
import {Injectable} from '@angular/core';
@Injectable()
export class UserProfileService {
isLoggedIn: boolean;
constructor() {
}
setLoggedInStatus(status) {
console.log('status: ', status);
this.isLoggedIn = status;
console.log('this.isLoggedIn : ', this.isLoggedIn) //setting to true or false here
}
getLoggedInStatus() {
return this.isLoggedIn;
}
}
但是,当我试图使用getLoggedInStatus()获取值时,每次都会得到未定义的值。
为什么会这样
此处设置
import {Component} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {SharedService} from '../../shared.service';
import {UserProfileService} from '../../authComponent/login/user-profile.service';
@Component({
selector: 'login',
templateUrl: 'app/components/authComponent/login/login.component.html',
providers: [SharedService, UserProfileService]
})
export class LoginComponent implements OnInit {
matched: boolean = false;
constructor(private sharedService: SharedService, private userService: UserProfileService) {
}
ngOnInit() {
this.myForm = new FormGroup({
email: new FormControl('', [Validators.required]),
password: new FormControl('', [Validators.required])
})
}
submit({value, valid}) {
if (!valid) {
return;
}
else {
this.sharedService.getData('users')
.subscribe(result => {
console.log('result: ', result, 'value passed: ', value)
result.forEach((record) => {
if ((record.email == value.email && record.password == value.password) && !this.matched) {
this.matched = true;
}
else {
this.matched = false;
}
});
if (!this.matched)
console.log('wrong credentials entered');
this.userService.setLoggedInStatus(this.matched);
})
}
}
}
import {Injectable} from '@angular/core';
import {
CanActivate,
CanActivateChild,
Route,
Router,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
import {UserProfileService} from './authComponent/login/user-profile.service';
@Injectable()
export class CanActivateAuthGuard implements CanActivate, CanActivateChild {
constructor(private userProfileService: UserProfileService, private router: Router) {
}
canActivateChild(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.canActivate(next, state);
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log('this.userProfileService.getLoggedInStatus: ', this.userProfileService.getLoggedInStatus())
if (this.userProfileService.getLoggedInStatus()) {
return true;
}
this.router.navigate(['/login'], {queryParams: {redirectTo: state.url}});
return false;
}
}
来到这里
import {Component} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {SharedService} from '../../shared.service';
import {UserProfileService} from '../../authComponent/login/user-profile.service';
@Component({
selector: 'login',
templateUrl: 'app/components/authComponent/login/login.component.html',
providers: [SharedService, UserProfileService]
})
export class LoginComponent implements OnInit {
matched: boolean = false;
constructor(private sharedService: SharedService, private userService: UserProfileService) {
}
ngOnInit() {
this.myForm = new FormGroup({
email: new FormControl('', [Validators.required]),
password: new FormControl('', [Validators.required])
})
}
submit({value, valid}) {
if (!valid) {
return;
}
else {
this.sharedService.getData('users')
.subscribe(result => {
console.log('result: ', result, 'value passed: ', value)
result.forEach((record) => {
if ((record.email == value.email && record.password == value.password) && !this.matched) {
this.matched = true;
}
else {
this.matched = false;
}
});
if (!this.matched)
console.log('wrong credentials entered');
this.userService.setLoggedInStatus(this.matched);
})
}
}
}
import {Injectable} from '@angular/core';
import {
CanActivate,
CanActivateChild,
Route,
Router,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
import {UserProfileService} from './authComponent/login/user-profile.service';
@Injectable()
export class CanActivateAuthGuard implements CanActivate, CanActivateChild {
constructor(private userProfileService: UserProfileService, private router: Router) {
}
canActivateChild(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.canActivate(next, state);
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log('this.userProfileService.getLoggedInStatus: ', this.userProfileService.getLoggedInStatus())
if (this.userProfileService.getLoggedInStatus()) {
return true;
}
this.router.navigate(['/login'], {queryParams: {redirectTo: state.url}});
return false;
}
}
在调用`setLoggedInStatus(..)之前,您是否调用了
getLoggedInStatus()
如果是这样,则从未初始化过isLoggedIn
boolean成员变量,因此,它仍然是未定义的
通过在声明isLoggedIn时初始化它,可以绕过此问题
export class UserProfileService {
isLoggedIn = false; // or true
.....
注意,我不必声明type-Typescript,它是根据初始化时使用的值推断出来的
编辑:
在您更新的帖子中,我注意到您将服务添加到组件的提供者列表中。基于您希望如何使用该服务,您不希望这样做。将服务添加到组件的提供者列表中或多或少地意味着我不希望此组件与其他任何人共享我的服务实例-我希望此组件拥有自己的服务实例
根据您的使用情况,您实际上希望将该服务添加到AppModule的提供者列表中
在调用`setLoggedInStatus(..)之前,您是否调用了
getLoggedInStatus()
如果是这样,则从未初始化过isLoggedIn
boolean成员变量,因此,它仍然是未定义的
通过在声明isLoggedIn时初始化它,可以绕过此问题
export class UserProfileService {
isLoggedIn = false; // or true
.....
注意,我不必声明type-Typescript,它是根据初始化时使用的值推断出来的
编辑:
在您更新的帖子中,我注意到您将服务添加到组件的提供者列表中。基于您希望如何使用该服务,您不希望这样做。将服务添加到组件的提供者列表中或多或少地意味着我不希望此组件与其他任何人共享我的服务实例-我希望此组件拥有自己的服务实例
根据您的使用情况,您实际上希望将该服务添加到AppModule的提供者列表中
angular中的服务是可注入的,这意味着在需要时调用它们。 如果您使用的是配置变量和全局变量,则可以通过在AppModule中声明来使用它们,如下所示
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<h2>{{name}} Sample</h2>
{{myConfiguration | json}}
</div>
`,
})
export class App {
name:string;
myConfiguration:any=myConfiguration;
constructor() {
console.log(myConfiguration);
this.name = 'Global Configuration'
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App]
})
export class AppModule {
var myConfiguration={id:1,devmode:true};
}
从'@angular/core'导入{Component,NgModule}
从“@angular/platform browser”导入{BrowserModule}
@组成部分({
选择器:“我的应用程序”,
模板:`
{{name}}样本
{{myConfiguration}json}
`,
})
导出类应用程序{
名称:字符串;
myConfiguration:any=myConfiguration;
构造函数(){
console.log(myConfiguration);
this.name='全局配置'
}
}
@NgModule({
导入:[BrowserModule],
声明:[App],
引导:[应用程序]
})
导出类AppModule{
var myConfiguration={id:1,devmode:true};
}
angular中的服务是可注入的,这意味着在需要时调用它们。 如果您使用的是配置变量和全局变量,则可以通过在AppModule中声明来使用它们,如下所示
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<h2>{{name}} Sample</h2>
{{myConfiguration | json}}
</div>
`,
})
export class App {
name:string;
myConfiguration:any=myConfiguration;
constructor() {
console.log(myConfiguration);
this.name = 'Global Configuration'
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App]
})
export class AppModule {
var myConfiguration={id:1,devmode:true};
}
从'@angular/core'导入{Component,NgModule}
从“@angular/platform browser”导入{BrowserModule}
@组成部分({
选择器:“我的应用程序”,
模板:`
{{name}}样本
{{myConfiguration}json}
`,
})
导出类应用程序{
名称:字符串;
myConfiguration:any=myConfiguration;
构造函数(){
console.log(myConfiguration);
this.name='全局配置'
}
}
@NgModule({
导入:[BrowserModule],
声明:[App],
引导:[应用程序]
})
导出类AppModule{
var myConfiguration={id:1,devmode:true};
}
要获得单例服务实例,只需将该服务作为提供者添加到一个模块中,而不在其他地方提供该服务 最简单的方法是将服务添加到
app.modules.ts
providers
app.module.ts:
@NgModule({
...
providers:[
UserProfileService
]
})
export class AppModule {}
这就足够了。要获得单例服务实例,只需将该服务作为提供者添加到一个模块中,而不在其他地方提供该服务 最简单的方法是将服务添加到
app.modules.ts
providers
app.module.ts:
@NgModule({
...
providers:[
UserProfileService
]
})
export class AppModule {}
这就可以了。您在一个组件中使用了
setLoggedInStatus
,在另一个组件中使用了getLoggedInStatus
,对吗?您是如何设置和获取的?您可能正在调用该服务的另一个实例。如果你不发布一个重现问题的例子,很难说为什么。@camaron:是的,用不同的方式components@BhushanGoel好吧,你的问题是JB Nizet指出的。您必须确保UserProfileService
仅由一个NgModule提供,而不是由其他地方提供。您正在一个组件中使用setLoggedInStatus
,而在另一个组件中使用getLoggedInStatus
,对吗?您是如何设置和获取的?您可能正在调用该服务的另一个实例。如果你不发布一个重现问题的例子,很难说为什么。@camaron:是的,用不同的方式components@BhushanGoel好吧,你的问题是JB Nizet指出的。您必须确保UserProfileService
仅由一个NgModule提供,而不是由其他地方提供。