Instagram API:如何在Angular 2/4/5中捕获access_token

时间:2018-07-25 13:49:52

标签: javascript angular instagram-api

我的angular 2项目正在实现以下Instagram身份验证:

  1. 注册Instagram客户端,添加沙盒用户(作为先决条件)
  2. 在signup.html中

    <button type="button" class="btn btn-round"(click)="signInWithInsta()"><i class="fa fa-instagram"> Instagram </i> </button>
    
  3. 在signup.component.ts

    import { Router, ActivatedRoute } from '@angular/router';
    
    constructor(
            private router: Router,
            private route: ActivatedRoute   
        ) { }
    
    ngOnInit() {
    
       this.route
                .queryParams
                .subscribe(params => {
                    console.log('params: ' + JSON.stringify(params));
                    let at = params['#access_token'];
                    console.log('access_token: ' + at);
                });
    
    }
    
    signInWithInsta(): void {
            let url =
                'https://api.instagram.com/oauth/authorize/?client_id=' + INSTAGRAM_CLIENT_ID +
                '&redirect_uri=' + encodeURIComponent('https://localhost:4200/index.html#/access_token') +
                '&response_type=token';
            console.log(url);
            window.location.href = url;
        }
    

结果: 我收到的日志是空的。

问题:如何从Instagram API捕获access_token。

对在Angular 2/4/5中实现Instagram登录的任何建议也表示赞赏

2 个答案:

答案 0 :(得分:0)

您可以使用const queryParams = this.route.snapshot.queryParams获取queryParams 我遇到了同样的情况,您的问题很有帮助!

答案 1 :(得分:0)

首先,根据Instagram的通知,基本用户详细信息API将在2020年初弃用。因此,请确保您签出用于Instagram登录here的新API并更新您的项目。< / p>

目前,您可以使用以下代码获取access_token:

this.activeRoute.queryParams.subscribe(params => {
  // if instagram code exist on url parameters, then it's user logged in using instagram
  if (params.code) {
    this.authService
      .instagramGetUserDetails(params.code)
      .subscribe(() => {
        // clear the code param from URL
        this.router.navigate([], {
          queryParams: { code: null },
          queryParamsHandling: 'merge'
        });
      });
  } else if (params.error) {
    // if error returned by instagram
  }
});

// get Instagram user details and token
instagramGetUserDetails(code) {
  try {
    const body = new HttpParams()
      .set('client_id', environment.instagram_client_id)
      .set('client_secret', environment.instagram_client_secret)
      .set('grant_type', 'authorization_code')
      .set('redirect_uri', environment.instagram_redirect_uri)
      .set('code', code)
      .set('auth', 'no-auth');

    return this.http
      .post(environment.instagram_get_token_uri, body.toString(), {
        headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
      })
      .pipe(
        tap(res => {
          // ----------->>>>>>   you get the token here   <<<<<---------------
          console.log(res.access_token)
        }),
        catchError(this.handleError<any>('instagram_auth'))
      );
  } catch (err) {
    return err;
  }
}

// Handle error
private handleError<T>(operation = 'operation', result?: T) {
  return (error: any): Observable<T> => {
    // TODO: send the error to remote logging infrastructure
    console.error(error); // log to console instead

    // TODO: better job of transforming error for user consumption
    console.log(`${operation} failed: ${error.message}`);

    // Let the app keep running by returning an empty result.
    return of(result as T);
  };
}