2016-10-04 51 views
0

我試圖整合角2 LinkedIn login,所有工作正常,但我得到的的WebPack幾個誤區,下面是我的代碼和我得到的錯誤:LinkedIn與角2

//linkedin.component.ts 
constructor(private zone: NgZone) { 
    window.angularComponentRef = { 
     zone: this.zone, 
     componentFn:() => this.onLinkedInLoad(), 
     component: this 
    }; 
} 

ngOnInit() { 
    // Creating script tag with linkedin src and required api details 
    var linkedinEle = document.createElement('script'); 
    linkedinEle.type = 'text/javascript'; 
    linkedinEle.src = 'http://platform.linkedin.com/in.js'; 
    linkedinEle.innerHTML = 'api_key: xxxxxxxxxxx \n authorize: true \n onLoad: onLinkedInLoad'; 
    document.head.appendChild(linkedinEle); 
} 
// this will called when the linkedin api gets load 
onLinkedInLoad() { 
    IN.Event.on(IN, "auth", function() { 
     console.log('Hell yeah'); 
    }); 
} 

// index.html 
function onLinkedInLoad() { 
    window.angularComponentRef.zone.run(function() { window.angularComponentRef.componentFn()}) 
} 

這所有人都做工精細,但在獲得的WebPack這樣的錯誤:

1. Property 'angularComponentRef' does not exist on type 'Window'. 
2. Cannot find name 'IN'. 

所以我想我可以通過聲明它像declare let IN: any但沒有運氣解決。

+0

包括你的代碼在ngAfterViewInit,而不是ngOnInit – Niyaz

+0

好的,但問題仍然存在 –

+0

將你的custruter中的東西移動到ngAfterViewInit – Niyaz

回答

1

使用窗口[「angularComponentRef」]和窗口[「IN」]代替或與此兩個字段

0

這是幾個月前,這一問題被問過,但我想反正回答延長窗口界面,因爲我們在一個項目中面臨類似的情況,甚至在我們發佈在npm(https://github.com/evodeck/angular-linkedin-sdk)的圖書館中提取了我們的解決方案。

  1. 好像你是從ngOnInit組件加載LinkedIn SDK。這會導致在每次加載組件時再次追加腳本標籤。更好地使用服務並在構造函數中完成。

  2. 在應用程序中使用窗口對象時,注入它而不是使用全局引用。

  3. 如上所述,如果您的窗口界面提供了它,或者使用any類型的窗口對象,請使用window['IN']window.IN。但不要與declare let IN: any

我希望它有幫助。不介意使用我們的libraray的源代碼。

0

我今天寫了一篇中篇文章,實際上是關於類似的問題。當角度釋放Angular Universal時,它首先呈現模板服務器端,用於性能和搜索引擎優化的原因。在這樣做時,它會失去對窗口對象的引用。

這裏是我的文章https://medium.com/@D_ofashandfire/i-love-hate-linkedin-oauth-2d7b602926c6

tldr,是該SDK在這種情況下真正打破。我發現使用REST API更容易,更簡單,然後通過服務器端實現接收認證碼。

這是一個示例組件。

https://gist.github.com/dashcraft/4b3853e558eaec656123342d1174912c

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'LinkedInExample', 
    template: '<a [href]="url">LinkedIn</a>' 
}) 

export class LinkedInExample{ 
    client_id: String = 'ClientStringHere'; 
    redirect_uri:String = encodeURI("http://localhost:5000/endpoint"); 
    url: String = `https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=${this.client_id}&redirect_uri=${this.redirect_uri}`; 
} 

當然,你可以把一個構造函數,OnInit的或類似的東西里面的性質,取決於你的應用程序流。

這將授權用戶並將它們返回給您的重定向uri,參數爲code,您可以通過Angular 2將它解析爲路由上的可選參數。