简体   繁体   English

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

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

I'm using Angular2 with Typescript. 我正在将Angular2与Typescript一起使用。 Say I have a dummy login component and an authentication service to do token authentication. 说我有一个虚拟的登录组件和一个身份验证服务来进行令牌身份验证。 I'm going to set the authenticated variable in one of the map function as soon as I get the token from backend server. 我将从后端服务器获取令牌后立即在map函数之一中设置authenticated变量。

The question is that I can't access the instance variable inside the chaining function. 问题是我无法访问链接函数内部的实例变量。 The this inside the chaining function is actually the subscriber of this observable. 链接功能内部的this实际上是该可观察的用户。 I know this's a scope issue but can't figure it out. 我知道这是一个范围问题,但无法解决。

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;
      });
}

The dummy-login component where the above login() method is called is like this: 调用上述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']);
        }
    })
  }
}

You can just subscribe to the observable instead of mapping it 您可以只订阅可观察对象,而不是映射它

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