扩展Angular2 +服务

时间:2017-09-12 13:54:12

标签: angular typescript types dependency-injection

我正在尝试使用空方法编写“基础”服务,其他开发人员应该为不同的后端系统编写“适配器”

以下是我的“基本”身份验证服务:

import { Injectable } from '@angular/core';
import { Http} from '@angular/http';
import {constants} from '../../constants/constants';


@Injectable()
export class ApiAuthServiceProvider {

  constructor(public http: Http) {
    console.log('Hello Base class ApiAuthServiceProvider Provider');

  }

  getVersion(credentials): Promise <any> {
    throw constants.NOT_IMPLEMENTED;
  }

  getToken (credentials): Promise <any> {
    throw constants.NOT_IMPLEMENTED;
  }

  getCredentials(): any {
    // do some stuff which is generic
    // and will be part of the base impleementation
  }


}

这是我建议的适配器,它为特定的后端扩展了这项服务

import { Injectable } from '@angular/core';
import { Http , URLSearchParams} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import {constants} from '../../../constants/constants';
import {ApiAuthServiceProvider} from '../../../providers/api-auth-service/api-auth-service';


@Injectable()
export class zmApiAuthServiceProvider extends ApiAuthServiceProvider {

  constructor(public http: Http) {
    super(http);
    console.log('Hello ZMApiAuthServiceProvider Provider');

  }

  getVersion(credentials): Promise <any> {
    return this.http.get (credentials.url+'/api/host/getVersion.json')
    .toPromise()
  }


  getToken(credentials): Promise <any> {
   // my stuff
 }
}

以下是我在app.component.ts

中关联适配器服务的方式
import {ApiAuthServiceProvider} from '../providers/api-auth-service/api-auth-service'
import {constants} from '../constants/constants';

// Classes for adapters in use
import {zmApiAuthServiceProvider} from '../adapters/zoneminder/providers/zm-api-auth-service';

@Component({
  templateUrl: 'app.html',
  providers: [
    {provide: ApiAuthServiceProvider, useClass: zmApiAuthServiceProvider}]
})

最后,在app.components.ts

的构造函数中调用
constructor(public auth: ApiAuthServiceProvider) {
this.auth.getToken(credentials)
}

尝试运行它会产生一大堆错误:

  
      
  • 合并声明'ApiAuthServiceProvider'中的个别声明必须全部导出或全部导出。
  •   
  • 导入声明与“ApiAuthServiceProvider”的本地声明冲突。
  •   
  • 模块'“xxx / src / adapters / zm / providers / zm-api-auth-service”'没有导出成员'zmApiAuthServiceProvider'。
  •   

我接近这个错误吗?感谢。

1 个答案:

答案 0 :(得分:0)

好吧,我不知道为什么当我发布时这不起作用 - 我可能没有保存一些东西!

这种方法非常有效 - 它可以是a)魔术b)我的省略

我会用魔法去。