标签: angular-services

如何动态实例化一个服务?

我有一项Utils非常繁重的服务。我想在特定用户操作上使用其中定义的一些功能。由于这项服务很重,我想懒惰地实例化它(根据用户操作)。

我如何实现这一目标?

服务

module.service('Utils', function (dep1, dep2) {
   this.method1 = function () {
      // do something
   }
   // other methods
});
Run Code Online (Sandbox Code Playgroud)

控制器

module.controller('AppCtrl', function ($scope) {
    // I don't want to inject Utils as a dependency.

    $scope.processUserAction = function () {
       // If the service is not instantiated 
       // instantiate it and trigger the methods defined in it. 
    }
});
Run Code Online (Sandbox Code Playgroud)

标记

<div data-ng-controller="AppCtrl">
    <button data-ng-click="processUserAction()"> Click Me </button>
</div>
Run Code Online (Sandbox Code Playgroud)

dependency-injection objectinstantiation angularjs angular-services

4
推荐指数
1
解决办法
8277
查看次数

将数据从一个组件传递到服务,然后传递到另一个组件

第一个组件.ts

onRecievingResults(value){
    console.log(value);
    this.faqService.saveData(value);
    console.log(value);
    this.router.navigate(['results'], {relativeTo: this.route});}
}
Run Code Online (Sandbox Code Playgroud)

在此onRecievingResults()函数中,单击按钮后,我将输入文本保存到saveData()名为 的服务中的方法faqService

服务.ts

saveData(value){
    console.log("save data function called " + value + this.sharingData.name);
    this.sharingData.name;
}
getData()
{
    console.log('get Data function called ');
    return this.sharingData.name;
}
getServers(name){
    return this.http.get(Staticdata.apiBaseUrl + "/2.2/search/advanced?key="+ Staticdata.key +"&access_token="+ Staticdata.access_token +"&/2.2/search/advanced?order=desc&sort=activity&accepted=True&closed=True&title=" + name + Staticdata.redirectUrl + "&filter="+ Staticdata.filters)
        .map(
        (response: Response) => {
            const items = response.json();
            return items;
        },
    )
    .catch(
        (error: Response) => {
            return Observable.throw(error);
        }
    );  
  }
} …
Run Code Online (Sandbox Code Playgroud)

observable typescript angular-services angular-components angular

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

Angular http post 通过服务将数据返回到组件

我想通过服务从sql server返回数据(@@identity)到组件

Web api 肯定被调用并发送回数据。

然而,由于我是 Angular 2/4 的新手(我习惯了 Angular 1),我通常只会 return在服务上执行操作,并为调用者设置一个变量或对象。

目前这就是我正在做的事情

成分

this.trackerFormService.addSession();  // CURRENT
Run Code Online (Sandbox Code Playgroud)

但由于该值是单个 id,例如 5,我不应该在打字稿中创建一些内容来检索它吗?

this.myId = this.trackerFormService.addSession();    // ???
Run Code Online (Sandbox Code Playgroud)

然后在服务中

private _url = 'http://localhost:60696/api/tracker';

addSession() { 
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    this.http.post(this._url, JSON.stringify({}), options).catch(this.handleError).subscribe();

}
Run Code Online (Sandbox Code Playgroud)

现在,对于上面的内容,将 ID 从服务(addSession() 方法)传递回组件,我不应该这样做吗return

return this.http.post(this._url, JSON.stringify({}), options).catch(this.handleError).subscribe();
Run Code Online (Sandbox Code Playgroud)

但这真的有效吗?

Web api (.net core) 看起来像这样

return Created($"api/sessiontrackers/{sessionTracker.Id}", sessionTracker);
Run Code Online (Sandbox Code Playgroud)

javascript observable typescript angular-services angular

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

如何在角度5中进行同步调用?

所以,我试图解决这个问题.但是,不知怎的,我无法这样做,可能是因为角度5缺乏知识.这是我的服务:

GetCurrentUserData(): Observable<ResponseData> {
    return this.http.get<ResponseData>(ApplicationURLS.GetCurrentUserInformation)
        .map(response => {
            return response;
        });
    //.catch(error => this.handleError(error));
}
Run Code Online (Sandbox Code Playgroud)

这是我的组成部分:

public GetCurrentUserInformation(): any {

        return this.loginService.GetCurrentUserData().subscribe(data => { return data; });
    }
Run Code Online (Sandbox Code Playgroud)

在这里,我试图访问数据:

ngAfterViewInit() {
        debugger;                
        this.responseData = this.GetCurrentUserInformation();
        if (this.responseData.code != responseCodes.success) {
            this.googleInit();
        }

    }
Run Code Online (Sandbox Code Playgroud)

当我检查this.responseData时,它总是返回此而不是我想要的数据: 在此输入图像描述

我只想进行同步调用,这样我就可以立即获取数据.

我也尝试在服务中使用do()但它返回的do()不是函数.

service angular-services angular-components angular angular5

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

从 Angular 中的 get Http 请求中获取标头

我正在调用一个获取 blob 数据的 API。

后端也向我发送标题中的文件名。

我的实际问题是我无法从 api 获取标题。

这是我的service.ts

public openFile(path) {
  let url='/download/';
  let pathFile= new HttpParams().set('pathFile', path);
  return this.httpClient.get(url,{params:pathFile, responseType: 'blob' });
Run Code Online (Sandbox Code Playgroud)

component.ts 中,我调用了该服务。当我尝试打印时,res.headers我在控制台中未定义。

openFile(path){
  this.creditPoliciesService.openFile(path).toPromise().then (data => {
    console.log("dataaaaaa",data.headers); // undefined
    var blob = new Blob([data], {type: 'application/pdf'}); 
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob);
    }
    else {
      var fileURL = URL.createObjectURL(blob); 
      window.open(fileURL);
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

在开发工具管理员中,我在响应标头中获得信息,但我无法在响应变量中找到它们。

httprequest http-headers typescript angular-services angular

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

Angular 6,在服务中调用函数时“无法读取未定义的属性”

我试图在服务中调用一个函数,但我一直有 Cannot read property 'authenticationService' of undefined

我已经authenticationService在组件的构造函数中初始化,

组件:

 export class RegisterComponent implements OnInit {
  error: string;
  isLinear = true;
  registerFormGroup: FormGroup;
  loading = false;
  form: FormGroup;
  studentRegister: any;
  samePassword = false;
  hide = true;
  hide1 = true;
  matcher = new MyErrorStateMatcher();

constructor(
   private router: Router,
   private _formBuilder: FormBuilder,
   private http: HttpClient,
   private i18nService: I18nService,
   private authenticationService: AuthenticationService
) {
}

ngOnInit() {
    this.registerFormGroup = this._formBuilder.group({
    first_name: [null, Validators.compose([Validators.required,                 Validators.minLength(3), Validators.maxLength(20)])],
    last_name: [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(20)])],
    email: [null, …
Run Code Online (Sandbox Code Playgroud)

http-post typescript angular-services angular angular-httpclient

4
推荐指数
1
解决办法
4265
查看次数

语法错误:JSON.parse 位置 1 处的 JSON 中的意外标记 e(&lt;匿名&gt;)

我想通过将 API 调用到 Angular 来获取字符串值。这是我正在做的服务文件 -

 public getRespondDashboardUrl(): Observable<any> {
    return this.http.get(`ref/RespondDashboardUrl`);
  }
Run Code Online (Sandbox Code Playgroud)

组件文件

respondDashboardLink: string;
this.refService.getRespondDashboardUrl().subscribe(result => {
  this.respondDashboardLink = result;
});
Run Code Online (Sandbox Code Playgroud)

函数返回 URL 作为字符串值https://abcd.xyz.com/Respond/App/index.html#ActionCenter/0

我得到的错误

SyntaxError: JSON.parse () at XMLHttpRequest.onLoad ( http://localhost:4000/vendor.js:33488:51 ) 在 ZoneDelegate.push../node_modules/zone.js/ dist/zone.js.ZoneDelegate.invokeTask ( http://localhost:4000/polyfills.js:8108:31 ) 在 ZoneDelegate 的 Object.onInvokeTask ( http://localhost:4000/vendor.js:78969:33 )。 push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask ( http://localhost:4000/polyfills.js:8107:60 ) 在 Zone.push../node_modules/zone.js/dist /zone.js.Zone.runTask ( http://localhost:4000/polyfills.js:7880:47 ) 在 ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke ] (http://localhost:4000/polyfills.js:8183:34 ) 在 invokeTask ( http://localhost:4000/polyfills.js:9429:14 ) 在 XMLHttpRequest.globalZoneAwareCallback ( http://localhost:4000/polyfills. js:9466:21 )

json angular-services angular

4
推荐指数
1
解决办法
6901
查看次数

Angular UI-router设置网站入口点.重定向到主页URL

我正在使用Angular和UI路由器,我希望用户始终(或者在大多数情况下,但为了简洁,我们可以说"总是")在我的主页step1上进入web应用程序.

UI路由器配置速记:

.config(function($stateProvider, $urlRouterProvider) {

    // route to root if no valid route found
    $urlRouterProvider.otherwise('/step1');

    var step1 = {
        name : 'step1',
        url : '/step1',
        templateUrl: 'partials/step1.html'
    };
    var step2 = {
        name : 'step2',
        url : '/step2',
        templateUrl: 'partials/step2.html'
    };
    .
    .
    .
    .
}
Run Code Online (Sandbox Code Playgroud)

我可以做一个解决方案或指定一个控制器,只需设置$ location.path('/ step1'),但是有一种方法可以设置一个入口点,并且步骤2 /步骤3的URL只能在从步骤1开始后才能到达,没有重定向的成本?
提前致谢

javascript angularjs angular-services angular-ui-router

3
推荐指数
2
解决办法
4350
查看次数

AngularJS控制器/工厂返回未定义的对象

工厂restful web api调用后,角度控制器结果未定义.我看过很多关于这个的帖子,但似乎都没有解决我的问题.我有一个控制器,可以进行一次宁静的web api2调用.使用fiddler我可以看到调用和200响应,但我似乎永远无法得到结果,我知道get是通过异步.以下是工厂和控制器.我也尝试将回调显式发送到工厂,这种方法甚至不会导致未定义的对象结果,只是不起作用.我真的处于停滞状态,我是Angularjs的新手,出了什么问题?目前我将控制器调用连接到一个按钮进行显式测试.

**FACTORY NO EXPLICIT CALL-BACK** 
casenoteApp.factory('MyFactory', function ($http) {


var factory = {};

var urlBase = 'http://xxxxxx/api/Client';


factory.getClients = function (userLogin) {

    return $http.get(urlBase + '/' + userLogin);
};


return factory;
});

**CONTROLLER NO EXPLICIT CALL-BACK** 
casenoteApp.controller('MyController', MyController);

function MyController($scope, MyFactory) {


$scope.addCustomer = function () {

    MyFactory.getClients(123456)
       .success(function (clients) {

            var curCust = clients;
            $scope.status = clients.last_name;

        })
       .error(function (error) {
           $scope.status = 'Unable to load client data: ' + error.message;
       });        

}


}

**FACTORY PASSING …
Run Code Online (Sandbox Code Playgroud)

angularjs angular-services

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

错误TS2339:类型'Observable <any>'上不存在属性'catchError'

这是我在book.service.ts中的代码:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs';
import { Book } from './book';
import { map } from "rxjs/operators";
import { catchError } from 'rxjs/operators';

//import { Component, OnInit } from '@angular/core';
//import {HttpClient} from "@angular/common/http";
//import { Observable } from 'rxjs/Observable'; 
//import 'rxjs/add/operator/map';
//import 'rxjs/add/operators/catch';
//import 'rxjs/operators/toPromise';

@Injectable()
export class BookService 
{
    url = "http://localhost:4200/assets/data/books.json";

    constructor(private http:Http) { }

    getBooksWithObservable(): Observable<Book[]> 
    {
        return this.http.get(this.url)
                .pipe(map(this.extractData))
                .catchError(this.handleErrorObservable);
    }
    getBooksWithPromise(): …
Run Code Online (Sandbox Code Playgroud)

angular-services angular

3
推荐指数
2
解决办法
6391
查看次数