我正在尝试使用使用新角度CLI创建的Angular2项目中的FB SDK。我创建了以下服务来初始化Facebook库,添加了fbsdk类型和所有编译但我无法从项目中的任何位置访问FB全局变量但是“winwow.fbAsyncInit”函数。我可以完美地从控制台检查FB对象,但无法从NG2代码访问它。 ¿想知道问题可能在哪里?
$array = array("a", "b", "c", "d");
$result = "";
foreach ($array as $a)
{
if ($result != "") { $result .= " & "; }
$result .= $a;
}
// $result = "a & b & c & d"
答案 0 :(得分:1)
密钥是在this.zone.run(callback)
的调用中包装回调并将其重新插入Angular 2生命周期。
我在服务构造函数中初始化SDK,与立即加载相比可能会引入一些延迟。尚未找到解决方法。
我还没有决定一旦初始化或包装方法我是否会提供FB
的访问者,我会留给你。
@Injectable()
export class FbsdkService {
public ready = new BehaviorSubject<boolean>(false);
constructor(
private zone: NgZone) {
this.loadSdkAsync(() => {
FB.init({
appId: "XXXXXXXXXXX",
status: false,
xfbml: false,
version: "v2.7"
});
this.ready.next(true);
});
}
loadSdkAsync(callback: () => void) {
window.fbAsyncInit = () => this.zone.run(callback);
// Load the Facebook SDK asynchronously
const s = "script";
const id = "facebook-jssdk";
var js, fjs = document.getElementsByTagName(s)[0];
if (document.getElementById(id)) return;
js = document.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs)
}
}
答案 1 :(得分:1)
我有类似的问题,这个来源帮助了我很多 - Building CrossPlatform Desktop Applications with Electron
import { Injectable, NgZone } from '@angular/core';
import { BehaviorSubject } from "rxjs/Rx";
import { Http } from '@angular/http';
declare var FB: any;
@Injectable()
export class FbsdkService {
public ready = new BehaviorSubject<boolean>(false);
public endpointBase = 'http://graph.facebook.com';
constructor(private zone: NgZone, private http: Http) {
}
public loadSdk() {
this.loadAsync(() => { });
}
public loadAsync(callback: () => void) {
window.fbAsyncInit = () => this.zone.run(callback);
const s = "script";
const id = "facebook-jssdk";
var js: any, fjs = document.getElementsByTagName(s)[0];
if (document.getElementById(id)) return;
js = document.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}
public getLoginStatus() {
FB.getLoginStatus((response: any) => { console.log(response); });
}
public getProfile() {
return new Promise((resolve, reject) => {
let fields = [
"id", "name", "email", "cover", "birthday"
];
FB.api(`/me?fields=${fields.toString()}`, (response: any) => {
resolve(response);
});
});
}
}