2016-10-04 68 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将它解析为路由上的可选参数。