Angular 2中的var引用

时间:2016-07-15 12:19:47

标签: angular

我有appComponent,还有this.loggedIn = this.authenticationService.isLogged;

因此appComponent使用authenticationService并从中获取isLogged数据。我想this.loggedIn引用了服务数据?

现在我从appComponent运行方法:

logout() {
    this.authenticationService.isLogged = false;
}

this.loggedIn应更改为false。但它没有。

这是appComponent.ts的一部分:

import {AuthenticationService} from './auth_service/auth_service';
@Component({
selector: 'my-app',
styleUrls: ['app/app_component.css'],
templateUrl: './app/main_app_template.html',
directives: [ ROUTER_DIRECTIVES],
providers: [ SendLoginService, AuthenticationService, ConfigurationService, SetupIntervalService]
})

export class AppComponent  {
loggedIn ;
constructor (private authenticationService: AuthenticationService
}
ngOnInit () {
    this.loggedIn = this.authenticationService.isLogged;
}
 logout() {
    this.authenticationService.isLogged = false;
    console.log(this.loggedIn);   //returns:  true . but should return 'false'
}

authenticationService.ts:

import {Injectable} from '@angular/core';
@Injectable ()
 export class AuthenticationService extends HttpBaseClass {
isLogged = true;
  }

4 个答案:

答案 0 :(得分:0)

这是因为对诸如boolean,string或number之类的基本类型的引用将不起作用(这就是JavaScript的工作原理)。如果你将isLogged包裹在一个对象中,那将会很好:

userAuth ={
    isLogged:true
}

答案 1 :(得分:0)

包括布尔值的基本类型由值表示。因此,如果您更新服务实例中的值

,则declare asd PCK.DATES_ARRAY_TYPE := PCK.DATES_ARRAY_TYPE('31-JUL-15', '01-AUG-15', '02-AUG-13', '03-AUG-13'); begin pck.test_case(asd); end; 不会发生变化
this.loggedIn

JS typesprimitive

答案 2 :(得分:0)

您能否使用此代码更新您的服务,如果您的问题仍然存在,请告诉我们?

[openssl]
openssl.cafile = /usr/local/etc/openssl/cert.pem

并像这样更新您的AppComponent -

import {Injectable} from '@angular/core';
@Injectable ()
 export class AuthenticationService extends HttpBaseClass {
     isLogged:boolean = true;

      logout(){
          isLogged = false;  
     }

     isLoggedIn(){
          return isLogged;
     }

  }

答案 3 :(得分:0)

发生因为值传递副本(值)而不是引用,您需要使用 authenticationService 并直接访问 authenticationService.isLogged 传递新值;

作为请求,示例

import {AuthenticationService} from './auth_service/auth_service';
@Component({
    selector: 'my-app',
    styleUrls: ['app/app_component.css'],
    templateUrl: './app/main_app_template.html',
    directives: [ROUTER_DIRECTIVES],
    providers: [SendLoginService, AuthenticationService, ConfigurationService, SetupIntervalService]
})
export class AppComponent {
    constructor(private authenticationService: AuthenticationService) { }

    logout() {
        this.authenticationService.isLogged = false;
        console.log(this.authenticationService.isLogged);   //now should returns false
    }
}