2017-07-26 77 views
0

我向Angular2站点添加功能以显示当前登录用户的名称。无限HTTP请求订阅可观察到的后端

我似乎能够从后端服务检索我需要的信息。但是,当正在运行的前端代码正在运行时,只有一个请求需要时,才会反复发送对后端的请求并尽可能快地发送。

当我更改代码以订阅observable时,开始了无限循环的请求。在没有订阅的情况下,我能够从前端服务中获取的信息不可用;它看起来像下面的例子。

{"_isScalar":false,"source":{"_isScalar":false},"operator":{}} 

组件

loggedInUser() { 
    this.authService.loggedInUser().subscribe(res => { 
     this.currentUser = res; 
     return this.currentUser; 
    }) 
} 

前端服务

loggedInUser() { 
    const userId = localStorage.getItem('userId'); 
    return this.http 
     .get('http://localhost:3000/user/current/' + userId) 
     .map((response: Response) => { 
    const user = response.json(); 
    return user; 
}) 

我了解到,这并不是真正意义上的 “无限循环” 从堆栈溢出阅读其他职位。但是,我无法理解那些其他职位的解决方案。

谢谢您的帮助!

回答

0

不确定没有小提琴,但你是否直接从模板调用组件的loggedInUser函数?

在组件中,认购代码移到ngOnInit

include { Component, OnInit } from '@angular/core'; 
... 
class AppComponent implements Oninit { 

    ngOnInit() { 
    this.authService.loggedInUser().subscribe(res => { 
     this.currentUser = res; 
    }); 
    } 
} 

参考this.currentUser模板

<div>Logged in as: {{currentUser}}</div> 

最好也unsubscribeNgOnDestroy

0

简单的方法是在用户登录后将您的信息存储在localStorage中,然后简单地读取它。

//In your authService 
loggedInUser() { 
    return this.http.post(AppSettings.API_URL + 'login', data, this.options) 
    .map((response: Response) => { 
     let username = response.json().data.username; 
     if(username){ 
      localStorage.setItem('username', username); 
      return true; 
     } else { 
      return false; 
     } 
    } 

//In your login form component 
onSubmit() { 
    this.authService.loggedInUser(email, ....) 
     .subscribe(
      result => { 
       if (result === true) { 
        //It's ok 
       } 
      error => { 
       //error 
      } 
     ) 
} 

如果你想订阅只有一次,你可以使用取操作。 当您离开一个组件或导航到另一个组件时,不要忘记取消订阅您的可观察项(在ngOnDestroy方法中执行此操作)。

0

您可以使用.retry函数,以便只发送有限次数的请求。

你可以写这样的事情:

loggedInUser() { 

    const userId = localStorage.getItem('userId'); 

    return this.http 

     .get('http://localhost:3000/user/current/' + userId) 

     .retry(1) 

     .map((response: Response) => { 

    const user = response.json(); 

    return user; 

}) 

此代码,如果是第一次申请失败,它会再试一次。

仅供参考,您可以在这里看到 - http://reactivex.io/documentation/operators/retry.html