2016-07-20 5 views
5

У меня проблема с аутентификацией LinkedIn в Angular2, мой код есть.Как интегрировать Linkedin в Angular2

import {Component , OnInit , NgZone} from 'angular2/core'; 
import {HTTP_PROVIDERS} from 'angular2/http'; 
import {ROUTER_DIRECTIVES , Router} from 'angular2/router'; 

declare var IN : any; 

@Component({ 
    directives : [ROUTER_DIRECTIVES], 
    selector : '.main', 
    providers : [HTTP_PROVIDERS], 
    templateUrl : './app/registration/employee.reg.html' 
}) 

export class EmployeeRegistrationComponent implements OnInit{ 

constructor(private zone : NgZone){ 
    this.zone.run(() => { 
     $.proxy(this.OnLinkedInFrameworkLoad, this); 
    }); 
} 

ngOnInit(){ 
    var linkedIn = document.createElement("script"); 
    linkedIn.type = "text/javascript"; 
    linkedIn.src = "http://platform.linkedin.com/in.js"; 
    linkedIn.innerHTML = "\n"+ 
     "api_key: **********\n" + 
     "authorize: true\n" + 
     "onLoad:" + this.OnLinkedInFrameworkLoad ; 
    document.head.appendChild(linkedIn); 

    var script = document.createElement("script"); 
    script.type = "in/Login"; 
    document.body.appendChild(script); 
} 

OnLinkedInFrameworkLoad =() => { 
    IN.Event.on(IN, "auth", this.OnLinkedInAuth); 
} 

OnLinkedInAuth =() => { 
    IN.API.Profile("me").result(result => this.ShowProfileData); 
} 

ShowProfileData(profiles) { 
    console.log(profiles); 
    var member = profiles.values[0]; 
    var id=member.id; 
    var firstName=member.firstName; 
    var lastName=member.lastName; 
    var photo=member.pictureUrl; 
    var headline=member.headline; 

    //use information captured above 
    } 

} 

консоли Бросив Ошибка: angular2-polyfills.js:1250 Uncaught Error: Could not execute 'function() {'. Please provide a valid function for callback.

Пожалуйста, помогите мне, что не так я делаю ...

+0

так угловато позволяет добавить тег сценария к йот? –

+0

yes .. Поскольку я использую javascript dom функции .. для обработки тегов сценариев –

+0

@DoubleH Вы когда-нибудь заставляли это работать? Мне сложно выполнить это, и там мало документации о том, как сделать что-то подобное. – pwborodich

ответ

1

Я нашел проблему путем проверки вывода исходного кода в первом тэгом.

Вопрос в том, где вы положили:

"onLoad:" + this.OnLinkedInFrameworkLoad; 

Это будет выводиться как:

onLoad: function() {↵   IN.Event.on(IN, "auth", _this.OnLinkedInAuth);↵  } 

И, как говорится в официальной документации developper

Внимание!

Разрыв строки между аргументами в тегах важен, поскольку нет другой формы разделителя полей. Если вы используете язык шаблонов или мини-код кода, который удаляет пробелы из отображаемого HTML, имейте в виду, что вам нужно будет сделать исключение, чтобы сохранить разрывы строк в этом теге, иначе они не будут правильно разбираться.

Источник: https://developer.linkedin.com/docs/getting-started-js-sdk


Я пока не нашел, как решить проблему входа в LinkedIn с угловыми 2, но я попробую еще раз другие решения

0

это работает для меня:

import { Component, OnInit, NgZone } from '@angular/core'; 

    export class RegistrationComponent implements OnInit{ 

constructor(private ngZone: NgZone) { 
     window['onLinkedInLoad'] =() => ngZone.run(() => this.onLinkedInLoad()); 
     window['displayProfiles'] = (profiles) => ngZone.run(() => this.displayProfiles(profiles)); 
     window['displayProfilesErrors'] = (error) => ngZone.run(() => this.displayProfilesErrors(error)); 
    } 

    ngOnInit() { 
       var linkedIn = document.createElement("script"); 
         linkedIn.type = "text/javascript"; 
         linkedIn.src = "http://platform.linkedin.com/in.js"; 
         linkedIn.innerHTML = "\n" + 
          "api_key: ****\n" + 
          "authorize: true\n" + 
          "onLoad: onLinkedInLoad\n"+ 
          "scope: r_basicprofile r_emailaddress"; 
         document.head.appendChild(linkedIn); 
         var script = document.createElement("script"); 
         script.type = "in/Login"; 
         document.body.appendChild(script); 
       } 

       public onLinkedInLoad() { 
         IN.Event.on(IN, "auth", this.onLinkedInProfile); 
       } 

       public onLinkedInProfile() { 
          IN.API.Profile("me") 
           .fields("id", "firstName", "lastName", "email-address") 
           .result(this.displayProfiles) 
           .error(this.displayProfilesErrors); 
       } 
       public displayProfiles(profiles) { 
        console.log(profiles); 
       } 
       public displayProfilesErrors(error) { 
         console.debug(error); 
       } 
       //Invoke login window with button 
       public liAuth() { 
        IN.User.authorize(function() { 
          console.log('authorize callback'); 
        }); 
       } 
      } 
0

Использование функции javascript dom, поэтому вам необходимо изменить это:

"onLoad:" + this.OnLinkedInFrameworkLoad ; 

Для этого:

"onLoad: onLinkedInLoad"; 

Теперь добавьте к этому <head> вашего index.html

<script type="text/javascript"> 

// Setup an event listener to make an API call once auth is complete 
function onLinkedInLoad() { 
    IN.Event.on(IN, "auth", getProfileData); 
} 

// Handle the successful return from the API call 
function onSuccess(data) { 
    console.log(data); 
} 

// Handle an error response from the API call 
function onError(error) { 
    console.log(error); 
} 

// Use the API call wrapper to request the member's basic profile data 
function getProfileData() { 
    IN.API.Raw("/people/~").result(onSuccess).error(onError); 
} 

</script> 
Смежные вопросы