2017-03-13 95 views
2

我想將PubNub添加到angular2-cli項目。問題在於鏈接;但是,我遵循npmjs.com上的pubnub-angular2軟件包的說明。將pubnub添加到angular2 cli項目

當我嘗試加載它在瀏覽器中,該錯誤信息是這樣的:

例外:PubNub是不是在全球範圍內。確保pubnub.js V4 庫角適配器

app.module.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提供商。

在此先感謝。

+1

我從來沒有使用過這個庫,但似乎錯誤是非常簡單的,你didin't導入主庫只是角度適配器。您需要將庫包含在您的vendor.ts中,例如'import「myLibrary」'或將其添加到index.html。在使用它的組件/服務中導入'pubnub-angular2'之前。 – n00dl3

+0

是的,它真的很直接;然而,解決方案對我來說並不是那麼微不足道。 vendor.ts是我無法更改的第三方庫,而當我引用index.html中的node_modules目錄時,瀏覽器找不到任何內容(節點模塊與src位於同一級別,index.html位於src文件夾)。 –

回答

2

從我可以從你的代碼告訴你可能被唯一缺少的是在您的index.html所需的腳本代碼,請務必在添加此...

<script src="node_modules/pubnub/dist/web/pubnub-angular2.js"></script> 

這裏是一個plunker的pudnub被適當地提升。

plunker

編輯

所有步驟,以確保你沒有跳過任何...

  1. NPM安裝NPM安裝pubnub

  2. NPM安裝pubnub,angular2

  3. 包括腳本的index.html(見上面的腳本

  4. 進口app.module import { PubNubAngular } from 'pubnub-angular2';

  5. 使用pubnub服務import { PubNubAngular } from 'pubnub-angular2';

    添加提供商app.module providers: [ PubNubAngular ]

  6. 導入任何組件

Angular-cli EDIT

從您的索引中刪除<script>標記。HTML並將其添加到您的angular-cli.json文件中像這樣...

"scripts": ["../node_modules/pubnub/dist/web/pubnub.js", "./node_modules/pubnub-angular2/dist/pubnub-angular2.js" ],

+0

謝謝。在安裝pubnub-angular2之後,它的路徑是另一個引用:''。由於我有一個級別的node_modules,我也試着用「../」開頭。在這兩種情況下,都會引發404錯誤。 –

+0

@HorvathAdam導航到你的'node_modules'文件夾,你看到'pubnub-angular2'嗎? – Bean0341

+0

@HorvathAdam另外,您可能實際上並不需要'