我是 Angular 新手,无法将用户信息从 LinkedIn API 保存到 Controller 中的范围,而不将范围传递给我的自定义服务。我认为这不是 Angular 编程方式。
//html
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: *********
onLoad: onLinkedInLoad
</script>
// linkedIn button
<script type="in/Login">
</script>
// app.js
angular.module("linkedinTestApp",[]);
function onLinkedInLoad(){
eScope.$apply(function(){
eScope.getLinkedInData();
})
};
// main controller
var eScope;
angular.module("linkedinTestApp").
controller('mainCtrl',function($scope,linkedInService){
eScope = $scope;
$scope.getLinkedInData = function(){
linkedInService.OnLinkedInFrameworkLoad($scope);
}
})
//custom service
angular.module('linkedinTestApp')
.service('linkedInService', function() {
var scope;
this.OnLinkedInFrameworkLoad = function(s) {
scope = s;
IN.Event.on(IN, "auth", this.OnLinkedInAuth);
console.log("Test1");
}
this.OnLinkedInAuth = function() {
IN.API.Profile("me").result(function(result){
console.log(result);
var profile = {
vnaam: result.values[0].firstName,
anaam: result.values[0].lastName,
foto: result.values[0].pictureUrl,
headline: result.values[0].headline,
id: result.values[0].id
}
console.log(profile);
scope.profile = profile;
});
console.log("Test2");
}
});
最佳答案
经过测试的代码。我花了 20-30 分钟来获取 api key ,当我测试时有人发布了答案,但我的代码经过了测试,所以发布了这个类似的答案。另外,这不是在 Controller 中获取配置文件的最优雅的方法,但我想更改尽可能少的代码(为了相似)。
angular.module("linkedinTestApp",[]);
function onLinkedInLoad(){
eScope.$apply(function(){
eScope.getLinkedInData();
})
};
// main controller
var eScope;
angular.module("linkedinTestApp").
controller('mainCtrl',function($scope,linkedInService){
eScope = $scope;
$scope.getLinkedInData = function(){
linkedInService.OnLinkedInFrameworkLoad().then(function(profile){
console.log('response ', profile);
});
}
})
//custom service
angular.module('linkedinTestApp')
.service('linkedInService', function($q) {
this.OnLinkedInFrameworkLoad = function() {
var deferred = $q.defer();
IN.Event.on(IN, "auth", function(){
deferred.resolve(OnLinkedInAuth())
});
return deferred.promise;
}
function OnLinkedInAuth() {
var deferred = $q.defer();
IN.API.Profile("me").result(function(result){
console.log(result);
var profile = {
vnaam: result.values[0].firstName,
anaam: result.values[0].lastName,
foto: result.values[0].pictureUrl,
headline: result.values[0].headline,
id: result.values[0].id
}
deferred.resolve(profile);
});
return deferred.promise;
}
});
关于javascript - 如何使用自定义服务将 LinkedIn API 中的用户信息保存到 Angularjs Controller 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35202103/