angular 5 post请求返回两次

时间:2017-12-06 14:49:14

标签: angular post request

登录后,调用authservice,然后路由工作到profilecomponent。

然而,邮件请求被发送两次,我没有使用Cors所以我假设这不能是一个预检请求? profile.component.ts ngoninit似乎运行了两次,因为我第一次收到带有正确id的coinId,后跟一个未定义的coinId。

  5a273e34f5c5643e18c035dacoinId from profile2!
  main.f2eaf663cdbf963d2af8.bundle.js:1 undefinedcoinId from profile2!

我对这一切都很陌生,我正在考虑启动一个nginx服务器,但不确定是否能解决这个问题。

login.component.ts

   let url = 'http://localhost:3000/api/login';
   this.newService.login( url, user, user.username).subscribe(result => {

var value = result["user"];
var coinId = result.user.coinid;
this.router.navigate(['/profile', coinId]);

auth.service.ts

  login(url: string, user: any, username: any)
  {return this.http.post(url , user)
  .do (res => this.setSession(res))
  }

  private setSession(authResult) {

        const expiresAt = moment().add(authResult.expiresIn,'second');
        this.loggedIn.next(!!localStorage.getItem('id_token'));

      console.log(authResult.token + "dit is de token");
        localStorage.setItem('id_token', authResult.idToken);

        localStorage.setItem("expires_at", JSON.stringify(expiresAt.valueOf()) );

    }     

profile.component.ts

 ngOnInit() {
  var coinId = this.route.snapshot.params['id'];
 console.log(coinId + "coinId from profile2!")


    this.router.navigate( [ '/profile', {outlets: { formOutlet: 
    ['profileform', coinAId]}}] );
   }

1 个答案:

答案 0 :(得分:0)

我对Angular很新,但您可以使用 shareReplay() 来避免多播POST请求。当您对同一个Observable进行多次订阅时,RxSwift会提供不同的运算符,并希望确保您的代码不会再次为订阅重新执行。再次或直到订阅过期。可用的运算符是replay(),replayAll(),publish(),share()和shareReplay()。

尝试更改您的代码,如下所示:

login(url: string, user: any, username: any)
  {return this.http.post(url , user)
  .do (res => this.setSession(res))
  .shareReplay()
  }

shareReplay()确保单个订阅。 shareReplay将在发送这些事件后,将来自可观察源的事件重播给订阅者。根据文件:

  

返回一个可观察序列,该序列共享对基础序列的单个预订,重放通知,其次数取决于重放缓冲区的最大时间长度。此运算符是连接到的重放的特殊化   当观察者的数量来自时,可连接的可观察序列   零到一,并在没有更多观察者时断开连接。

Github Docs & Example

Also See this question on Stackoverflow with simplified explanation