简体   繁体   English

Angular 9 无法发帖请求

[英]Angular 9 can't make a post request

I'm currentry just a begginner in Angular,我现在只是 Angular 的初学者,

I'm trying make a post request using this function:我正在尝试使用此 function 发出帖子请求:

 signIn(user: User) {
    console.log("1");
    return this.http
      .post<any>(`${this.endpoint}/login`, user)
      .subscribe((res: any) => {
        console.log("2");
        localStorage.setItem("access_token", res.token);
        this.getUserProfile(res._id).subscribe(res => {
          this.currentUser = res;
          this.router.navigate(["user-profile/" + res.msg._id]);
        });
      });
  }

I tried to monitor the network (using the network tab in firefox), and I've found out that no data is sent.我试图监视网络(使用 Firefox 中的网络选项卡),我发现没有发送任何数据。

When opening the console it displays "1" but not "2".打开控制台时,它显示“1”而不是“2”。

Thank you谢谢

You need to return the observable and subscribe to it there.您需要返回 observable 并在那里订阅它。 Now you are returning a subscription so you might not know when actually the call is triggered.现在您正在返回订阅,因此您可能不知道实际何时触发了调用。 Also try to avoid nested subscriptions.还要尽量避免嵌套订阅。 You could use RxJS higher order operators (like switchMap ) to pipe multiple observables.您可以使用 RxJS 高阶运算符(如switchMap )到 pipe 多个可观察对象。 Try the following尝试以下

some service一些服务

signIn(user: User) : Observable<any> {
  return this.http.post<any>(`${this.endpoint}/login`, user).pipe(
    switchMap((user) => {
      localStorage.setItem("access_token", user.token);
      return this.getUserProfile(user._id);
    }
  );
}

component零件

ngOnInit() {
  this.someService.signIn(user).subscribe(
    res => {
      this.currentUser = res;
      this.router.navigate(["user-profile/" + res.msg._id]);
    },
    (error) => {
      // always good practice to handle HTTP observable errors
    }
  );
}

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

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