【问题标题】:Angular2/Typescript: access instance variable from the chaining observable functionAngular2/Typescript:从链式可观察函数访问实例变量
【发布时间】:2016-04-14 20:57:31
【问题描述】:

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

问题是我无法访问链接函数内的实例变量。链接函数内部的this 实际上是这个 observable 的订阅者。我知道这是一个范围问题,但无法弄清楚。

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()方法被调用的dummy-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']);
        }
    })
  }
}

【问题讨论】:

  • 不确定,但看看这是否有帮助:stackoverflow.com/a/34948742/215945
  • @MarkRajcok 不是真的,我已经在另一个组件中订阅了这个 observable。我真正想做的是在.map() 函数中将authenticated 实例变量设置为true。
  • 调用login的代码在哪里?要么修复该代码,要么将 login 设为箭头函数
  • 为什么你认为它不起作用?箭头函数从上下文中捕捉到这一点。
  • 调试器可能稍微关闭(由于源映射导致错误行),请尝试在DummyLoginComponent 中添加this.auth.authenticated 的日志记录。

标签: javascript typescript angular


【解决方案1】:

你可以只订阅 observable 而不是映射它

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多