我的 Angular 2 项目正在实现 Instagram 身份验证,如下所示:
- 注册 Instagram 客户端,添加沙箱用户(作为前提条件)
在signup.html中
<button type="button" class="btn btn-round"(click)="signInWithInsta()"><i class="fa fa-instagram"> Instagram </i> </button>
在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 登录的建议也值得赞赏
最佳答案
首先,根据Instagram通知,基本用户详细信息 API 将于 2020 年初弃用。因此,请务必查看用于 Instagram 登录的新 API here并更新您的项目。
目前,您可以使用以下代码来获取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);
};
}
关于javascript - Instagram API : how to catch access_token in Angular 2/4/5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51520605/