标签: angular-services

如何在Angular服务中使用jQuery.cookie插件

我一直试图ngCookie在我的应用程序中存储和检索cookie.由于我无法设置创建的cookie的路径或到期ngCookie,我不得不寻找其他地方.

所以我试图使用这个jQuery cookie插件.

However, I can't figure out how to make it available in an angular service. Gooling around for how to make jQuery plugins available in controllers and services, the answers unanimously point to using directive, but I don't think that's the right approach in this case since cookies are something controllers and services should be aware of.

So, how would someone make a jQuery plugin available to an Angular service?

jquery angularjs angular-services

3
推荐指数
1
解决办法
2809
查看次数

Angular.js resourceProvider返回带有数据的$ promise

给出angular.js服务:

angular.module('mymodule').factory('Products', ['$resource',
    function($resource) {
        return $resource('/path/to/getProducts', {}, {
            find: {
                method: 'GET',
                isArray: false
            }
        });
    }
]);
Run Code Online (Sandbox Code Playgroud)

mymodule我的控制器中find查询:

$scope.findAll = function () {
    Products.find(function (products) {
        console.log(Object.keys(products));
        // ['prodA', 'prodB', ... , '$promise', '$resolved']
        for (var i in products) {
            if (!products.hasOwnProperty(i)) continue;
            console.log(products[i].description.someprop);
            // Got error: Cannot read property 'someprop' of undefined
            // Trust me: I debug this place. someprop is defined for all items except that two
        }
    });
};
Run Code Online (Sandbox Code Playgroud)

它工作正常,但返回$ promise和$使用数据集解析,因此我无法遍历我的数据. …

javascript rest resourceproviderfactory angularjs angular-services

3
推荐指数
1
解决办法
1566
查看次数

服务不会注入控制器

我过去曾做过一些Angular应用程序,但从未真正使用过模块.我现在正在创建一个Ionic应用程序(使用Angular),由于某种原因,我无法将我的服务注入控制器.

controllers.js

angular.module('myapp.controllers', [])
.controller('StreamCtrl', ['$scope', 'StreamService',
function($scope, StreamService) {
    $scope.playlists = [1,2,3,4];
}]);
Run Code Online (Sandbox Code Playgroud)

services.js

angular.module('myapp.services', [])
.factory('StreamService', ['$scope', function($scope) {
    var self = {
        'fetching' : false,
        'streamItems' : []
    };
    return self;
]);
Run Code Online (Sandbox Code Playgroud)

app.js

angular.module('myapp', ['ionic',
                        'myapp.services',
                        'myapp.controllers',
                        'ngCordova',
                        'LocalStorageModule'])
// And lots of other code that isn't needed for this question.
Run Code Online (Sandbox Code Playgroud)

因此,当我尝试加载时,StreamCtrl我最终收到以下错误:

Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <-StreamService
http://errors.angularjs.org/1.3.6/$injector/unpr?p0=<ion-nav-view name="menuContent" class="view-container" nav-view-transition="ios">copeProvider%20%3C-%20%24scope%20%3C-%20StreamService
at REGEX_STRING_REGEXP (http://localhost:8100/lib/ionic/js/ionic.bundle.js:7888:12)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:11806:19
at Object.getService [as get] (http://localhost:8100/lib/ionic/js/ionic.bundle.js:11953:39)
at …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs angularjs-factory angular-services ionic-framework

3
推荐指数
1
解决办法
2979
查看次数

将参数传递给服务构造函数?

我正在尝试在组件中实例化服务。我收到这个错误

未捕获的错误:无法解析 AuthenticationService 的所有参数:(?, [object Object], ?)。

这是我的服务

     @Injectable()
    export class AuthenticationService {

      protected basePath = 'http://localhost:8080/rest';
      public defaultHeaders: Headers = new Headers();
      public configuration: Configuration = new Configuration();

      constructor(protected http: Http, @Optional() @Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
        if (basePath) {
          this.basePath = basePath;
        }
        if (configuration) {
          this.configuration = configuration;
          this.basePath = basePath || configuration.basePath || this.basePath;
        }
      }

    public login(authenticationkey?: string, body?: AuthenticationRequestHolder, extraHttpRequestParams?: any): Observable<AuthenticationBundle> {
        return this.loginWithHttpInfo(authenticationkey, body, extraHttpRequestParams)
          .map((response: Response) => {
            if …
Run Code Online (Sandbox Code Playgroud)

typescript angular-services angular

3
推荐指数
1
解决办法
7741
查看次数

在我的情况下,如何将服务注入模块?

我正在尝试将旧的 angular 1.5 服务注入到我的 angular 1.5/4 混合应用程序中的 angular 4 模块中。

MyService,因为如果我让一个市民,我也没办法与初次它使用一个静态方法 new MyService(),因为MyService预计设置了一个param,我不知道如何提供。

我的班级 (my-service.class.ts)

import {Inject, Injectable} from '@angular/core';

@Injectable()

class MyService {
    constructor(
      @Inject('myOldService') private myOldService: any) {}

    static getMyUrl() {  
        console.log(this.myOldService); 
        // complains    
        // Property 'myOldService' does not exist on type 'typeof MyService
        return this.myOldService.getItemUrl();
    }
}

export default MyService;
Run Code Online (Sandbox Code Playgroud)

我的模块

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';

...other import..

import MyService from './my-service.class';

console.log(MyService.getMyUrl())
//has error …
Run Code Online (Sandbox Code Playgroud)

typescript angular-services angular-module angular

3
推荐指数
1
解决办法
6396
查看次数

angular - 在所有组件中共享模态

我正在尝试实现自定义确认对话框功能,该功能计划在应用程序范围内可用 - 跨所有组件。

为此,我使用Angular Material.

模态是一个单独的组件,我通过以下方式在另一个组件中解析它:

const dialogRef = this.confirmDialog.open(ConfirmDialogComponent, ... });
Run Code Online (Sandbox Code Playgroud)

我面临的问题 -使用这种方法我必须在每个组件中复制代码DRY principle被侵犯。

更多细节:

...
export class SearchComponent extends AppComponentBase {...

    constructor(public confirmDialog: MatDialog, ...) { super(injector); }

    confirm(title: string, message: string) {
        var promise = new Promise((resolve, reject) => {

            const dialogRef = this.confirmDialog.open(ConfirmDialogComponent, {
                width: '250px',
                data: { title: title, message: message }
            });

            dialogRef.afterClosed().subscribe(result => {
                if (result) {
                    resolve();
                } else {
                    reject();
                }
            });
        }); …
Run Code Online (Sandbox Code Playgroud)

singleton refactoring angular-services angular-material angular

3
推荐指数
1
解决办法
2281
查看次数

将 Angular 服务注入到导出的函数中?

我在 AppComponent 中定义了以下导出函数(类外):

export function multiTranslateHttpLoaderFactory(http: HttpClient) {
  return new MultiTranslateHttpLoader(http, [
    {prefix: './assets/i18n/default/', suffix: '.json'},
    {prefix: './assets/i18n/bc/', suffix: '.json'}
  ]);
}
Run Code Online (Sandbox Code Playgroud)

然后以这种方式在 AppModule 的导入数组中使用它:

TranslateModule.forRoot ({
  loader: {
    provide: TranslateLoader,
    useFactory: multiTranslateHttpLoaderFactory,
    deps: [HttpClient]
  }
}),
Run Code Online (Sandbox Code Playgroud)

我需要一种在导出函数中使用我的 AuthService 的方法,因为我需要某些属性来实现逻辑。

有没有可能?

例如,我想以这种方式使用我的 authService:

export function multiTranslateHttpLoaderFactory(http: HttpClient) {
  let bc = this.authService.activeBusinessCase$.getValue();
  if(bc){
    ...
  }else{
    return new MultiTranslateHttpLoader(http, [
      {prefix: './assets/i18n/default/', suffix: '.json'},
      {prefix: './assets/i18n/bc/', suffix: '.json'}
    ]);
  }
}
Run Code Online (Sandbox Code Playgroud)

dependency-injection function typescript angular-services angular

3
推荐指数
1
解决办法
7301
查看次数

是否仍然需要 Angular 服务模块?

在 angular 文档中,它列出了可以实现的功能模块的类型。其中之一是服务模块。

https://angular.io/guide/module-types

在早期版本的 Angular 中,您将创建您的服务并将其列在服务 NgModule 的 providers 数组中。然后这个 NgModule 将由消费应用程序导入,其中服务将在应用程序根注入器中提供。

Injectable()
export class MyService {}

NgModule({
    providers: [MyService]
})
export class MyServicesModule {}

NgModule({
    imports: [MyServicesModule]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

最新的 Angular 建议是使用 Injectable 注释,您不再需要在提供程序定义中列出它。

Injectable({ providedIn: 'root'})
export class MyService {}
Run Code Online (Sandbox Code Playgroud)

因此,创建服务模块有什么意义吗?您是否只是使用上述注释在根注入器中创建您想要提供的服务,然后直接导入服务类并相应地注入?

dependency-injection angular-services angular

3
推荐指数
1
解决办法
2424
查看次数

我们如何在 angular 服务中使用 forwardRef 来避免循环依赖?

我已经阅读了几篇关于在 angular 中解决循环依赖的文章,所有文章都提到了使用 forwardRef 来解决循环依赖。我在网上找到的所有参考资料都只涉及组件服务交互。

我的场景是这样的:

如果两个服务相互依赖并且导致类循环依赖问题。我找不到与使用 forwardRef 相关的适当线程或任何解决两个服务之间循环依赖的最佳方法。

如果有人遇到任何此类类似的问题并就如何处理此问题提出建议,那将是可观的。

我知道循环依赖是可以避免的,但是如果我们需要以适当的方式进行,那么我应该采用什么方法?

谢谢

forward-reference angular-services angular

3
推荐指数
1
解决办法
1970
查看次数

为什么在共享服务中使用 BehaviorSubject 而不是使用简单的共享变量?

我对使用 BehiavorSubject 而不是在服务中使用共享变量有点困惑。如果我创建一个带有共享变量的服务,甚至覆盖它们,Angular 组件也会检测到这些变化,那么我为什么要使用 BehiavorSubject 而不是共享变量?例如,在我的项目中,我有一个导航栏,如果用户登录就会显示该导航栏,所以我有 ngIf service.isLoggedIn 并且它工作正常。为什么我需要一个服务中的 observable 并订阅它的事件。如果有人从不同的组件更改此值,它也会在此处更改。我是 angular 的新手,如果我遗漏了什么,请告诉我。谢谢(我正在关注这个例子:https : //loiane.com/2017/08/angular-hide-navbar-login-page/

observable angular-services behaviorsubject angular

3
推荐指数
1
解决办法
719
查看次数