我想将 PubNub 添加到 angular2-cli 项目中。问题出在链接上;但是,我按照 npmjs.com 上 pubnub-angular2 包的说明进行操作。
当我尝试在浏览器中加载它时,错误消息是这样的:
例外:PubNub 不在全局范围内。确保 pubnub.js v4
库包含在角度适配器之前
In the 应用程序模块.ts,我有以下内容:
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http';
import {PubNubAngular} from 'pubnub-angular2';
import {AppComponent} from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [PubNubAngular],
bootstrap: [AppComponent]
})
export class AppModule {}
在 app.component.ts 中,我有以下代码:
import {Component, Injectable, Class} from '@angular/core';
import {PubNubAngular} from "pubnub-angular2";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Pubnub Chat Service';
private channel = 'chat-demo-app';
constructor(private pubnubService: PubNubAngular) {
pubnubService.init({
publishKey: 'pub-c-***',
subscribeKey: 'sub-c-***'
});
}
sendMessage(message: string): void {
this.pubnubService.publish({
channel: this.channel,
message: message
});
}
}
请注意,如果我删除 AppComponent 中的导入,该组件将看不到 PubNubAngular 提供程序。
提前致谢。
从我从你的代码中可以看出,你可能缺少的唯一一件事是你的index.html中需要的脚本标签,确保你添加这个......
<script src="node_modules/pubnub/dist/web/pubnub-angular2.js"></script>
这是一个笨蛋pudnub
得到妥善实施。
plunker https://plnkr.co/edit/jz9z6wArruL04qa2IY6h?p=preview
EDIT
确保您没有跳过任何步骤的所有步骤...
npm 安装 npm 安装 pubnub
npm 安装 pubnub-angular2
将脚本包含到index.html(参见上面的脚本
导入到app.moduleimport { PubNubAngular } from 'pubnub-angular2';
将提供者添加到app.moduleproviders: [ PubNubAngular ]
使用 pubnub 服务导入到任何组件import { PubNubAngular } from 'pubnub-angular2';
Angular-cli 编辑
去除<script>
标签从你的index.html并将其添加到你的angular-cli.json
像这样的文件...
"scripts": ["../node_modules/pubnub/dist/web/pubnub.js", "./node_modules/pubnub-angular2/dist/pubnub-angular2.js" ],
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)