【问题标题】:Angular2 custom npm packageAngular2 自定义 npm 包
【发布时间】:2016-11-17 04:06:00
【问题描述】:

我想为我在多个应用程序中使用的身份验证服务编写一个 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"
 }
}

我的索引.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:/// .... "
}

导入成功,模块将导入到 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'

这个错误是由模块移植引起的。将其声明为提供者也不起作用。错误是一样的。

有谁知道如何为 angular2 创建自己的自定义插件以及如何正确注入它们?

【问题讨论】:

  • 尽量在Providers中使用Authenticate而不是imports,imports主要是为了modules声明。
  • 它抛出相同的执行。在模块的构造函数中声明类变量会不会有问题?

标签: angular npm


【解决方案1】:

问题是我模块中的构造函数参数:

constructor(
     private http:Http, 
     private authUrl:string) {
   this.authUrl = Config.authUrl;

}

当我直接在课堂上声明它们时,模块工作了:

export class Authenticate {
      http: Http;
      authUrl:strin;

      constructor(){
          console.log("constructor without params");
      }
 }

angular2 npm 模块似乎不喜欢构造函数中的参数。

Furter(正如 Michał 所说):模块必须放在提供者处,而不是导入处。

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 2020-10-17
    • 2017-04-14
    • 1970-01-01
    • 2019-11-08
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多