0
我想爲我在幾個應用程序中使用的身份驗證服務編寫一個npm模塊。我看了一下其他軟件包,但是找不到很大的區別。Angular2自定義npm包
我的模塊部分::
我的package.json:
{
"name": "myApi-services",
"version": "1.0.0-11",
"main": "index.js", //referring to the compiled js file from index.ts
"dependencies": {
"@angular/common": "2.1.0",
"@angular/core": "^2.1.0",
"@angular/http": "^2.1.0",
"@angular/platform-browser": "^2.1.0",
"angular2-jwt": "^0.1.25",
"rxjs": "5.0.0-beta.12",
"zone.js": "^0.6.21"
}
}
我Index.ts
export { MyAuthService} from "./authenticate"
我的身份驗證類
import { Http, Headers } from '@angular/http';
import { Config } from './config'
export class Authenticate {
constructor(private http:Http, private authUrl:string) {
this.authUrl = Config.authUrl;
}
public login(username:string, password:string): void {
let headers = new Headers();
headers.append('Authorization', 'Basic ' + btoa(username + ':' + password));
headers.append('Accept', 'application/json');
this.http.post(this.authUrl, {}, { headers: headers })
.subscribe(
response => {
this.storeToken(response.json().token);
},
err => console.log(err),
() => console.log('Request Complete')
);
}
private storeToken(token: string):void{
localStorage.setItem('apiservices_token', token);
console.log(localStorage.getItem('apiservices_token'))
}
}
我的導入部分::
的package.json
"depenencies":{
"MyApi-services": "file:/// .... "
}
進口工程,模塊得到importes到node_modules文件夾
app.module.ts
import { Authenticate } from 'myApi-services'
@NgModule({
imports:[ Authenticate ]
})
app.component.ts
import { Authenticate } from 'myApi-services'
...
constructor(private auth: Authenticate){}
private login():void{
auth.login('me', '12345');
}
....
一個瀏覽器引發的錯誤:
Uncaught Error: Unexpected value 'Authenticate' declared by the module 'AppModule'
此錯誤是由imorting模塊引起的。將它聲明爲提供者也是行不通的。錯誤是一樣的。
有誰知道如何爲angular2創建自定義插件以及如何正確插入它們?
嘗試在提供程序中使用Authenticate而不是導入,導入主要用於模塊聲明。 –
它引發相同的執行。它可能是一個問題,在模塊的構造函數中聲明類變量? – marcel