我将google登录javascript翻译成打字稿,并且它有效,我遇到的问题是我无法访问google登录功能中的_router变量。在attachSignin()函数里面,我尝试从构造函数中访问_router:Router param,我得到的是未完成的。
这是我的代码
import {Component, NgZone} from "angular2/core";
import {ToastsManager } from 'ng2-toastr/ng2-toastr';
import {Router, ROUTER_PROVIDERS} from 'angular2/router'
// Google's login API namespace
declare var gapi: any;
@Component({
selector: "sous-app",
templateUrl: "app/login/login.html",
providers: [ToastsManager, ROUTER_PROVIDERS]
})
export class Login {
googleLoginButtonId = "google-login-button";
userAuthToken = null;
userDisplayName = "empty";
auth2 = null;
self = this;
constructor(
public _router: Router) { }
// Angular hook that allows for interaction with elements inserted by the
// rendering of a view.
ngAfterViewInit() {
var loginProxy = $.proxy(this.attachSignin, this);
var redirectToPolls = $.proxy(this.redirectToPolls, this);
gapi.load('auth2', function () {
// Retrieve the singleton for the GoogleAuth library and set up the client.
self.auth2 = gapi.auth2.init({
client_id: '718161509287-jdpqsuebcoteh847krjn0m1odnbo5i3q.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
// Request scopes in addition to 'profile' and 'email'
//scope: 'additional_scope'
});
loginProxy(document.getElementById('customBtn'));
});
}
attachSignin = (element) => {
var navigate = false;
console.log(element.id);
self.auth2.attachClickHandler(element, {},
function (googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
//HERE I WANT TO ACCESS ROUTER
_router.navigate(['Polls']);
console.log(googleUser.getAuthResponse().id_token);
}, function (error) {
alert(JSON.stringify(error, undefined, 2));
});
}
}
答案 0 :(得分:2)
将function()
更改为() =>
self.auth2.attachClickHandler(element, {},
(googleUser) => {