【问题标题】:core.js:9110 ERROR TypeError: Cannot read property 'post' of undefinedcore.js:9110 错误类型错误:无法读取未定义的属性“帖子”
【发布时间】:2019-11-25 13:10:45
【问题描述】:

我正在构建和 api 以在 Angular 中包含linkedin登录。我在这里使用Linkedin的文档一步一步地做到了: https://docs.microsoft.com/fr-fr/linkedin/shared/authentication/authorization-code-flow?context=linkedin/context

我控制台记录要发送的 url 以获得令牌,一切都很好,但我仍然有:“无法读取未定义的属性 'post'”。所有信息都在通过 post 发送的 url 中找到以获取结果。


    import { Injectable } from '@angular/core';
    import { Router } from '@angular/router';
    import {  HttpClient, HttpHeaders } from '@angular/common/http';

    //INTERFACE UTILISATEUR
    import { User } from './user.model';

    import { auth } from 'firebase/app';
    import { AngularFireAuth } from '@angular/fire/auth';
    import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';

    import { Observable, of, interval, Subscription } from 'rxjs';
    import { switchMap } from 'rxjs/operators';

    @Injectable({ providedIn: 'root' })

    export class AuthService {

    //PROPERTIES --------------
      user$: Observable<User>;
      state:string = '<hide>';
      clientID: String = '<hide>';
      keyID: String = '<hide>';
      urlLinkedin = `https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=${this.clientID}&redirect_uri=http://localhost:4200/authentification/sign-in&scope=r_liteprofile%20r_emailaddress%20w_member_social&state=${this.state}`;
      windowAttributes:string = "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=520,height=700";
      windowTarget:string = "_blank";
      codeRecup:string;
      subscription$: Subscription;
      sendURL:string;

    //END PROPERTIES --------------

    //CONSTRUCTOR
      constructor(
        private afAuth: AngularFireAuth,
        private afs: AngularFirestore,
        private router: Router,
        private http:HttpClient
      ) {}

    //Linkedin  ---------------------- 
    linkedinSignin(){
        window.open(this.urlLinkedin, this.windowTarget, this.windowAttributes);
        window.addEventListener('message', this.linkedinGetCode, false);
      }

    linkedinGetCode (event){
      this.clientID =  '<hide>';
      this.keyID = '<hide>';

      if (event.origin !== "http://localhost:4200")
      return;
      this.codeRecup = event.data;

      this.sendURL = `https://www.linkedin.com/oauth/v2/accessToken`+
      `&grant_type=authorization_code`+
      `&code=${this.codeRecup}`+
      `&redirect_uri=http://localhost:4200/authentification/sign-in`+
      `&client_id=${this.clientID}&client_secret=${this.keyID}`;

    //URL to get the token is perfect
      console.log(this.sendURL);

      this.http.post(this.sendURL,{headers: new HttpHeaders({'Host': 'www.linkedin.com', 'Content-Type':'application/x-www-form-urlencoded'})}
        ).subscribe(responseData =>
          {
            console.log(responseData), err => console.error(err)
          });
      event.preventDefault();
    }

【问题讨论】:

    标签: angular


    【解决方案1】:

    我猜你正在失去上下文。试试这个

    window.addEventListener('message', this.linkedinGetCode.bind(this), false);
    

    【讨论】:

    • 您好,非常感谢您的时间和回答。现在它正在工作我从linkedin得到答案,并添加了你的解决方案。你能解释一下我在哪里失去了上下文吗?当我在控制台记录 URL 时,它很好。就在将它发送到 http.post 之前。
    • 我找到了有关 Binding 的这些信息,您将其放入您的回复中:stackoverflow.com/questions/2236747/…
    • @Jeremie-Segu 因为您将函数分配给回调,这可能导致丢失this(指向另一个对象)。我们可以通过存储上下文或使用绑定来防止。更多解决方案:stackoverflow.com/questions/43490761/ionic-2-set-interval/…
    • 非常感谢,我会好好研究这个解决方案并将其应用到我的代码中。祝您有美好的一天,再次感谢您的再次光临。
    【解决方案2】:

    使用 Tiep Phan 解决方案的代码:

    linkedinSignin(){
        window.open(this.urlLinkedin, this.windowTarget, this.windowAttributes);
        window.addEventListener('message', this.linkedinGetCode.bind(this), false);
      }
    
    linkedinGetCode (event){
      this.clientID =  'hide';
      this.keyID = 'hide';
      //Si le message en provenance du Child a une autre origine que la  Window parente alors on stop tout
      if (event.origin !== "http://localhost:4200")
      return;
      //On récupère le code pour générer un TOKEN
      this.codeRecup = event.data;
      //console.log(this.codeRecup);
      //On prépare l URL pour POSTER le code et recevoir le TOKEN
      this.sendURL = `https://www.linkedin.com/oauth/v2/accessToken`+
      `&grant_type=authorization_code`+
      `&code=${this.codeRecup}`+
      `&redirect_uri=http://localhost:4200/authentification/sign-in`+
      `&client_id=${this.clientID}&client_secret=${this.keyID}`;
      console.log(this.sendURL);
      this.http.post(this.sendURL,{headers: new HttpHeaders({'Host': 'www.linkedin.com', 'Content-Type':'application/x-www-form-urlencoded'})}
        ).subscribe(responseData =>
          {
            console.log(responseData), err => console.error(err)
          });
      event.preventDefault();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-02
      • 2020-07-22
      • 2021-04-05
      • 2021-03-12
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      相关资源
      最近更新 更多