繁体   English   中英

Angular2 / Typescript:从链接可观察函数访问实例变量

[英]Angular2/Typescript: access instance variable from the chaining observable function

我正在将Angular2与Typescript一起使用。 说我有一个虚拟的登录组件和一个身份验证服务来进行令牌身份验证。 我将从后端服务器获取令牌后立即在map函数之一中设置authenticated变量。

问题是我无法访问链接函数内部的实例变量。 链接功能内部的this实际上是该可观察的用户。 我知道这是一个范围问题,但无法解决。

export class AuthenticationService {
authenticated:boolean = false; //this is the variable I want to access

constructor(public http: Http) {
    this.authenticated = !!sessionStorage.getItem('auth_token');
}

login(username, password) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http
      .post(
        'http://localhost:8080/token-auth',
        JSON.stringify({ username, password }),
        { headers }
      )
      .map(res => res.json())
      .map((res) => { 
        if (res) {
            this.authenticated = true;  //this is where I want to access the instance variable
            sessionStorage.setItem('auth_token', res.token);
        }

        return res;
      });
}

调用上述login()方法的虚拟登录组件如下所示:

export class DummyLoginComponent {
  constructor(private auth: AuthenticationService, private router: Router) {
  }

  onSubmit(username, password) {

    this.auth.login(username, password).subscribe((result) => {
        if (result) {
            this.router.navigate(['Dashboard']);
        }
    })
  }
}

您可以只订阅可观察对象,而不是映射它

login(username, password) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    let res = this.http
      .post(
        'http://localhost:8080/token-auth',
        JSON.stringify({ username, password }),
        { headers }
      )
      .map(res => res.json());
    res.subscribe(
      (res) => { 
            this.authenticated = true;  //this is where I want to access the instance variable
            sessionStorage.setItem('auth_token', res.token);
    });
    return res;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM