ERROR TypeError: Cannot read property 'navigate' of undefined when trying to navigate to another component after webapi response

ERROR TypeError: Cannot read property 'navigate' of undefined when trying to navigate to another component after webapi response

我正在尝试使用来自 here 的社交登录并实施并且工作正常

  1. 我正在尝试让用户使用 google 登录 - 工作正常
  2. 正在尝试访问登录用户的详细信息并将其发送到 Web api - 工作正常
  3. returns 来自网络的结果 api - 工作正常
  4. 问题出现在成功注册后,我得到的响应是“成功” 根据结果​​,我试图将用户从主页组件导航到仪表板,如下所示。然后我无法导航他并向我抛出这个错误 “错误类型错误:无法读取未定义的 属性 'navigate'”

这是我的代码:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { SocialAuthService, GoogleLoginProvider, SocialUser } from 'angularx-social-login';
declare var $: any;
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})

export class HeaderComponent implements OnInit {
  socialUser: SocialUser;
  isLoggedin: boolean;  
  constructor(private router: Router,private socialAuthService: SocialAuthService) {}
}

ngOnInit() {
  this.socialAuthService.authState.subscribe((user) => {
    this.socialUser = user;
    this.isLoggedin = (user != null);
  });
    
  }
  loginWithGoogle(): void {
    this.socialAuthService.signIn(GoogleLoginProvider.PROVIDER_ID).then(user => {
      this.register(user);
   });    
  }

  logOut(): void {
    this.socialAuthService.signOut().then(() => this.router.navigate(['home']));
  }

  refreshGoogleToken(): void {
    this.socialAuthService.refreshAuthToken(GoogleLoginProvider.PROVIDER_ID);
  }

  register(user:any){
    var email = user.email
    var name = user.name
    var imageurl = user.photoUrl
    $.ajax({
      type: "POST",
      url: "https://localhost:44394/api/User/RegisterUser",
      data: JSON.stringify({
        LoginType : "google", Email: email, Name: name, ImageURL : imageurl
      }),
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (msg:any) {
        console.log(msg);
        if (msg === "True"){
          this.router.navigate(['dashboard']);
        }else if(msg === "Email exists"){
          this.router.navigate(['dashboard']);
        }else{
          this.router.navigate(['home']);
        }
      },
      error: function (msg:any) {
        this.router.navigate(['home']);
      }
    });

  }
}

这是我的路线module.ts

 import { DashboardComponent } from './dashboard/dashboard.component';
    
    { path :'dashboard', component:DashboardComponent,
      data: {
        title: "Dashboard Component",
        description: "",
        keywords: "",
        ogUrl: "https://example.net/dashboard"
    }
  }

发生这种情况是因为您正在从 jQyery Ajax 方法中访问 this.router。您需要将正确的上下文传递给回调方法(成功、错误等)。除非你这样做,否则 this 将不会指向我们在这里想要的组件实例。

要将 this 作为组件,您需要将组件 this 存储在一个单独的变量中,然后将该变量传递给 jQyery 提供的 context 选项:

将您的注册功能更改为:

    register(user:any){
       var email = user.email;
       var name = user.name;
       var imageurl = user.photoUrl;
       var that = this; // Here we are storing component this to that

       $.ajax({
         type: "POST",
         url: "https://localhost:44394/api/User/RegisterUser",
         data: JSON.stringify({
        LoginType : "google", Email: email, Name: name, ImageURL : imageurl
      }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        context: that, // Here we are passing the component this
        success: function (msg:any) {
        console.log(msg);
        if (msg === "True") {
          this.router.navigate(['dashboard']);
        } else if(msg === "Email exists"){
          this.router.navigate(['dashboard']);
        } else {
          this.router.navigate(['home']);
        }
      },
      error: function (msg:any) {
        this.router.navigate(['home']);
      }
    });
}

建议:避免在 Angular 应用程序中使用 jQuery Ajax。 Angular 有一个名为 HttpClient 模块的内置模块,您可以使用它来调用 API(s)。检查这个:https://angular.io/guide/http