标签: angular-services

Angular 4.x:没有服务提供者

我无法将服务注入Angular 4.x中的另一个服务并收到错误: Error: No provider for SkillsService!

我创建了一个repo来重现这个错误.您可以通过克隆repo本地运行它,只需ng test从repo根目录运行.

我采取的步骤......

  1. 使用创建应用 ng new
  2. 使用创建ContactService ng g service contact
  3. 使用创建SkillsService ng g service skills
  4. 将SkillsService添加到ContactService的构造函数(使用@Inject批注)
  5. 将SkillsService和ContactService作为提供者添加到app.module.ts
  6. 运行ng test并收到错误:Error: No provider for SkillsService!

如何为SkillsService的ContactService添加提供程序?

似乎它必须是非常简单的东西,但它很难从文档和搜索中解决.

angular-services angular

9
推荐指数
1
解决办法
1万
查看次数

通过angularjs中的服务编译指令

我正在尝试通过角度服务编译指令但不幸的是它不起作用.想法是在弹出窗口中显示错误.

我修改了$ exceptionHandler服务:

crm.factory('$exceptionHandler', function(popup) {
    return function(exception) {
        popup.open({message: exception});
    }
});
Run Code Online (Sandbox Code Playgroud)

弹出的服务如下:

crm.factory('popup', function ($document) {
    return {
        open: function (data) {
            var injector = angular.element(document).injector(),
                $compile = injector.get('$compile'),
                template = angular.element('<popup></popup>');

            // var ctmp = $compile(template.contents());
            $compile(template.contents());

            $document.find('body').append(template);
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

而且我不认为这是硬编码$ compile服务的好主意(但我没有任何想法如何在角度中实现这一点):

$compile = injector.get('$compile')
Run Code Online (Sandbox Code Playgroud)

弹出指令:

crm.directive('popup', function () {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: '/public/js/templates/common/popup.html',
        link: function() {
            console.log('link()');
        },
        controller: function () {
            console.log('ctrl()');
        } …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs angularjs-directive angular-services

8
推荐指数
1
解决办法
5453
查看次数

AngularJS获取当前工厂/服务名称

奥拉!

我正在玩角度的工厂和服务,我只是注意到我无法获得工厂/服务的当前名称.至少我无法获得任何相关资源.
例如,所以它有点清楚,我有一个像这样的工厂;

.factory('GuessImAFactory', [function() {

    var factoryName = this.yadayada.name; //<- This actually doesn't work,
                                             //if you haven't guessed

    //<--Some other code goes here-->

    return something;
}])
Run Code Online (Sandbox Code Playgroud)

那么问题是否有人知道如何获得它的名称的技巧?

javascript angularjs angular-services

8
推荐指数
1
解决办法
2354
查看次数

ES6服务(AngularJS)

在使用ES6创建服务时,我在访问Angular内置服务时遇到了问题,例如$ http.

例如,我正在创建一个"ResultsFinder"服务,它将执行一个AJAX调用然后做一些事情.问题是我只能在构造函数上访问$ http(如果我将其作为参数传递),而不是其他方法(例如getResults).

看到这个代码示例:

(() => {
  'use strict';

  class ResultsFinder {
    constructor($http) {}
    getResults() {
      return 'ResultsFinder';
    }
  }

  /**
   * @ngdoc service
   * @name itemManager.service:ResultsFinder
   *
   * @description
   *
   */
  angular
    .module('itemManager')
    .service('ResultsFinder', ResultsFinder);
}());
Run Code Online (Sandbox Code Playgroud)

在getResults内部,我无法访问$ http.为了获得访问权限,我应该做一些我感觉不正确的事情:

(() => {
  'use strict';

  class ResultsFinder {
    constructor($http) {
      this.$http = $http;
    }
    getResults() {
      // Here I have access to this.$http
      return 'ResultsFinder';
    }
  }

  /**
   * @ngdoc service
   * @name itemManager.service:ResultsFinder
   *
   * @description
   *
   */
  angular …
Run Code Online (Sandbox Code Playgroud)

javascript web-services angularjs ecmascript-6 angular-services

8
推荐指数
1
解决办法
1万
查看次数

使用AngularJS解决服务/工厂与控制器中的承诺

所以我已经玩过承诺在服务和控制器中解决.我宁愿在服务中解决它,所以我可以重用变量而不必多次解决它.

我遇到的问题是它有效,但它返回的数据非常缓慢.所以我觉得我在这里做错了.我的ng-options填充大约需要5或6秒.哪个更好?我如何改进我的代码,使其运行得更快?

已解决服务:

resortModule.factory('locaService',['$http', '$rootScope', function ($http, $rootScope){
    locaService.getLocations=
        function() {
            return $http.get('/api/destinations').then(
                function(result){
                    locaService.locations= result.data;
                    return locaService.locations;
                }
            );
        return locaService.locations;
    };
resortModule.controller('queryController',['$scope', 'locaService', function($scope, locaService) {
    $scope.getLocations= locaService.getLocations().then(function(result){
       $scope.locations= result;
    });
}]);
Run Code Online (Sandbox Code Playgroud)

已在控制器中解决:

resortModule.factory('locaService',['$http', '$rootScope', function ($http, $rootScope){
locaService.getLocations=
    function() {
        locaService.locations= $http.get('/api/destinations');
        //stores variable for later use
        return locaService.locations;
    };
}]);
resortModule.controller('queryController',['$scope', 'locaService',          
    function($scope, locaService) {
       locaService.getLocations()
       .then(
            function(locations) // $http returned a successful result
            {$scope.locations = locations;} //set locations to returned data
       ,function(err){console.log(err)});
}]);
Run Code Online (Sandbox Code Playgroud)

HTML:

<select …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs angular-services angular-promise

8
推荐指数
1
解决办法
1242
查看次数

确保实例化服务

背景

我们正在构建一个Angular2应用程序,并且正在积累与一个模块相关的许多特定服务.所有这些服务都松散地耦合到Subject<Type>应用程序中的事件系统.

通过构造函数实例化

因为这些服务永远不会被直接引用,只能订阅事件,所以我们只需要以某种方式实例化它们.目前我们只是将它们注入到另一个使用的服务的构造函数中.

// Services not used, just to make sure they're instantiated
constructor(
  private appService1: AppService1,     
  private appService2: AppService2,
  private appService3: AppService3,
  ...
){ }
Run Code Online (Sandbox Code Playgroud)

这看起来有点像黑客,是否有更好的方法来显式声明需要实例化的服务而不通过构造函数注入它们?

dependency-injection angular-services angular

8
推荐指数
1
解决办法
6440
查看次数

angular2多士炉 - 没有烤箱容器已经初始化以接收烤面包

我在角度应用中使用angular2-toaster

这很简单,

您在组件的模板中定义烤箱容器

<toaster-container></toaster-container>
Run Code Online (Sandbox Code Playgroud)

并且您使用类型的toasterService ToasterService来弹出烤面包机

  this.toasterService.pop('success', 'Args Title', 'Args Body');
Run Code Online (Sandbox Code Playgroud)

但是这种方法存在问题,我不想在我想要弹出烤面包机的每个组件中定义一个容器,我想在root组件中定义一次.应用程序引导程序,但当我这样做,我得到错误

 No Toaster Containers have been initialized to receive toasts.
Run Code Online (Sandbox Code Playgroud)

任何解决方案

typescript angular-services angular angular2-toaster

8
推荐指数
1
解决办法
7093
查看次数

测试Http Service进行多次调用并返回observable而不映射响应

我有一个数据服务,它从服务器获取数据并生成多个请求,然后返回一个可观察数组.我想测试数据.

我尝试做的是在我发送的mockrespone数组中包含两个observables我不知道这是否是测试数据的正确方法.

但测试失败,尤其是异步测试块中的最后三个测试

重要提示:我想测试一下,当将charId设置为falsy并将comicsId设置为falsy时,调用方法,订阅它返回的observable,在你模拟了http后,你会得到一个包含两个预期响应的数组.如果charId是真实的,则与预期的4个响应相同.当comicsId真实时,6个预期的响应也是如此

//获取数据的服务

getChar(): Observable<any> {

    const Observables = [];
    Observables.push(this.http.get('https://gateway.marvel.com:443/v1/public/characters?apikey'));
    Observables.push(this.http.get('https://gateway.marvel.com:443/v1/public/comics?apikey'));

    if (this.charId) {
      Observables.push(this.http.get(`${this.urlChar}${this.charId}${this.apiKey}`));
      Observables.push(this.http.get(`${this.urlChar}${this.charId}/comics${this.apiKey}`));
    }
    if (this.comicsId) {
      Observables.push(this.http.get(`${this.urlCom}${this.comicsId}${this.apiKey}`));
      Observables.push(this.http.get(`${this.urlCom}${this.comicsId}/creators${this.apiKey}`));
    }
    console.log([Observable, Observable]);
    return Observable.forkJoin(Observables);
  }
}
Run Code Online (Sandbox Code Playgroud)

//我的考试

import { async, ComponentFixture, TestBed, getTestBed, inject } from '@angular/core/testing';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { DataService } from './data.service';
import {
  BaseRequestOptions, Http, XHRBackend, HttpModule,
  Response, ResponseOptions, RequestMethod
} from '@angular/http';
import { Observable } from 'rxjs/Observable';

describe('DataService', () => {
  let …
Run Code Online (Sandbox Code Playgroud)

jasmine angular-http angular-services angular angular-test

8
推荐指数
1
解决办法
1102
查看次数

使用jasmine angular2注入私有服务的单元测试

我试图对角度服务进行单元测试时遇到问题.我想验证此服务是否正确调用注入其中的另一个服务.

假设我有这个注入ServiceInjected的ServiceToTest:

ServiceToTest .service.ts

@Injectable()
export class ServiceToTest  {
    constructor(private _si: ServiceInjected) {}
    public init() {
      this._si.configure();
    }

}
Run Code Online (Sandbox Code Playgroud)

ServiceInjected.service.ts

@Injectable()
export class ServiceInjected {
    constructor() {}
    public configure() {
    /*Some actions*/
    }

}
Run Code Online (Sandbox Code Playgroud)

有了这些服务,现在我编写单元测试:

const serviceInjectedStub = {
  configure(): void {}
}


describe('ServiceToTest service Test', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [ServiceToTest ,
        { provide: ServiceInjected, useValue: serviceInjectedStub }]
    });
  });
  
  it('should be initialize the service injected', inject([ServiceToTest],
    (tService: ServiceToTest) => {
      spyOn(serviceInjectedStub, 'configure');
      tService.init();
      expect(serviceInjectedStub.configure).toHaveBeenCalled();
    })); …
Run Code Online (Sandbox Code Playgroud)

injectable angular-services karma-jasmine spyon angular

8
推荐指数
2
解决办法
8790
查看次数

Angular 5下载带有帖子请求的excel文件

我正面临一个问题,我用Angular 1下载了一个Excel文件,但是如果我在Angular 5中实现了相同的代码,则会显示您的文件已损坏的错误.我的回复是在ArrayBuffer中,我无法读取该文件.

以下是我的代码:

服务:

 DownloadData(model:requiredParams):Observable<any>{
  const headers = new Headers();
  const requestOptions = new RequestOptions({ headers: headers });
  requestOptions.headers.append('Content-Type', 'application/json');

   const body = JSON.stringify(model);
  return this.http.post(url, body, requestOptions)
  .map((res:any) => res)
 .catch((e: any) => Observable.throw(this.errorHandler(e)));
 }
Run Code Online (Sandbox Code Playgroud)

零件:

exportToExcel() {
    this.loadingOverlayFlag = true;
   this.podashboardService.DownloadData(this.data).subscribe(result=>{
    console.log(result);
    this.downloadFile(result._body,'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'export.xlsx');
  })
  }

 downloadFile(blob: any, type: string, filename: string) {

 var binaryData = [];
   binaryData.push(blob);

     const url = window.URL.createObjectURL(new Blob(binaryData, {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})); // <-- work with blob directly

     // create hidden dom …
Run Code Online (Sandbox Code Playgroud)

angular-services angular

8
推荐指数
2
解决办法
8485
查看次数