标签: angular-httpclient

HttpClient未运行构造函数

我正在使用HttpClient从json端点获取对象。提取并订阅可观察对象后,我发现构造函数未在模型上运行,并且对象上的公共方法都未定义。如何使构造函数运行并且方法可用?

export class Customer {

    constructor() {
        this.Addresses = new Array<Address>();
        }

    public Addresses: Array<Address>;

    public addAddress(address: Address) void{
        this.Addresses.push(address);
    }
}

var url: string = `${this.urlBase}api/customer/${id}`;
var customerObservable: Observable<Customer> = this.authHttp.get<Customer>(url);

customerObservable.subscribe(customer => {
    // Addresses is undefined!
    customer.Addresses.push(new Address());
    // addAddress is undefined!
    customer.addAddress(new Address());
});
Run Code Online (Sandbox Code Playgroud)

angular angular-httpclient

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

Angular使用HttpClient测试服务对我来说不起作用

我正在开展一个Angular 5项目,这没什么大不了的.虽然我从2.1/2.2早期就已经离开了Angular2 +业务.

所以我有这个调用公共API的服务,但我的测试仍然失败: Error: Expected one matching request for criteria "Match URL: http://api.icndb.com/jokes/random/10", found none.

码:

fact.service.spec.ts

import {HttpClientTestingModule, HttpTestingController} from "@angular/common/http/testing";
import {TestBed, inject} from "@angular/core/testing";
import {FactService} from "./fact.service";
import {Fact} from "../models/fact";
import {FactHttpResponse} from "../models/factHttpResponse";

describe("FactService", () => {
    let factService: FactService;
    let httpMock: HttpTestingController;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [FactService],
        });
        httpMock = TestBed.get(HttpTestingController);
        factService =  TestBed.get(FactService);
    });

    // TODO: Something is going wrong with this test get some help online
    it("Should …
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-httpclient

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

如何处理HttpClient请求的日志记录?

我正在使用Angular和rxjs 5.xx.对于每个http请求,我必须在集中的位置记录响应 - 如果成功或失败.

我面临的问题是在调用一个catch条款的情况下.

例如 :

  callRemote() {
    return this.http.get("http://aaa.dom")
                    .catch(f=>Rx.Observable.of(f))
                    .do(f => console.log("logging response both bad and ok..."))
  }
Run Code Online (Sandbox Code Playgroud)

这是一个http失败的请求.但我必须调用do运算符,因为我需要记录它.但是,如果.catch调用a,.do则不会调用.这就是我这样做的原因:

  .catch(f=>Rx.Observable.of(f))
Run Code Online (Sandbox Code Playgroud)

所以我基本上捕获错误并将其包装为新的observable并继续执行该.do功能.

到现在为止还挺好.

现在的问题是,最终,订阅时,我想知道请求是否失败或确定.

基本上这就是我订阅的方式:

 this._http.callRemote().subscribe(
      (x => console.log('OK')),
      (x => console.log('ERROR')),
      (() => console.log('COMPLETE'))
    );
Run Code Online (Sandbox Code Playgroud)

问题是所有内容都被重定向到sucess回调函数.甚至失败.我明白为什么会发生这种情况 - 因为我catch作为新的Observables 包裹失败了.

包装错误是否可能转发error回调,而不是success回调?

在线演示

logging error-logging rxjs angular angular-httpclient

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

使用Angular中的httpclient.post发送和接收不同的类型

我需要调用Web服务,并在其中发送带有User对象的POST请求,并返回一个LogToken对象。

我找不到如何使用Angular httpClient进行此操作,因为它似乎期望发送和接收相同的类型。如果执行以下操作,则会出现错误:

  public login(user: User): Observable<LoginToken> {
    return this._httpClient.post<User>(this._authenticationServiceUrl, user);
  }
Run Code Online (Sandbox Code Playgroud)

错误TS2322类型'Observable {User}'无法分配给类型'Observable {LoginToken}'。

因为我对这项技术还很陌生,所以我想我做错了什么,但是不确定。从POST请求中接收其他类型是否错误?

post typescript angular angular-httpclient

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

角HttpClient结合管道,点击与订阅?

我正在尝试使用Angular中的HttpClient检索一些数据。我的代码如下所示:

getData(suffurl: string, id?:number): Observable<any[]> {
    return this.http.get<any[]>('localhost:5555/DNZ/'+ this.suff_url)
    .pipe(
      tap(data => console.log("Anlagenstatus Daten:", data)),
      catchError(this.handleError('getData',[])),
      subscribe(Response => { console.log(Response)})
    )
  }
Run Code Online (Sandbox Code Playgroud)

但是,我不能在管道方法中使用订阅,也不能在.pipe方法之前或之后将其链接。问题是,没有链接,尽管链接和数据存在,但似乎此代码未从url返回任何数据或未向控制台记录任何内容?

publish-subscribe angular angular-httpclient

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

@ angular / common / http没有导出的成员'RequestOptions'

我想使用Firebase函数使用角度为6的电子邮件打磨电子邮件,但是角度引发此错误:

错误TS2305:模块'“ E:/ project / node_modules / @ angular / common / http”'没有导出的成员'RequestOptions'。

import { Injectable } from '@angular/core';
import { NgForm } from '@angular/forms';
import { HttpClient, HttpHeaders, RequestOptions } from '@angular/common/http';
import 'rxjs';

@Injectable()
export class MailerService {

    constructor(private httpClient: HttpClient) { }

    send(form: NgForm) {

        let url = 'TheUrlOfMyFunction';
        let params: URLSearchParams = new URLSearchParams();
        let options = {headers: new HttpHeaders({'Content-Type':  'application/json'})};

        params.set('to', form.value['emailTo']);
        params.set('from', form.value['emailFrom']);
        params.set('subject', form.value['object']);
        params.set('content', form.value['text']);

        return this.httpClient.post(url, params, options)
                        .toPromise()
                        .then( res …
Run Code Online (Sandbox Code Playgroud)

angular angular-httpclient

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

Hack news API - 获取所有新闻

我有https://github.com/HackerNews/API的问题。

我需要在第一页的 30 条新闻(标题、作者...)中获取 Angular 7 中的所有最佳新闻。如何使用下一个 api 发送 get 请求?

此 API 显示最佳故事的所有 ID:https : //hacker-news.firebaseio.com/v0/topstories.json?print=pretty

这个 api 展示了一个故事的例子:https : //hacker-news.firebaseio.com/v0/item/8863.json?print=pretty

我试试这个:

loadItem(){
this.http.get(`https://hacker- 
news.firebaseio.com/v0/item/${this.id}.json?print=pretty`).subscribe(data => {
    this.items.push(data as any[]);
  })
}    

loadBestItems(){
this.http.get('https://hacker-news.firebaseio.com/v0/beststories.json? 
print=pretty').subscribe(data => {
            this.bestItems.push(data as any[]);
          })
 } 
Run Code Online (Sandbox Code Playgroud)

我需要第一页上的 30 条最佳新闻

html javascript css angular angular-httpclient

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

Angular 7 HttpClient put 请求参数向端点发送空值

我有一个带有这个 Put 请求方法的 Angular 服务:

put(peopleFieldID: number, peopleFieldName: string): Observable<number> {
let params = new HttpParams();
params = params.append("peopleFieldID", peopleFieldID.toString());
params = params.append("peopleFieldName", peopleFieldName);

return this.http
  .put<number>(this.url, { params: params })
  .pipe(catchError(this._errorHandling.handleError.bind(this)));}
Run Code Online (Sandbox Code Playgroud)

以上在我的 .net 核心 API 上命中了这个端点:

    [Authorize(Roles = "Client")]
    [Route("")]
    [HttpPut]
    public IActionResult C_Update(int peopleFieldID, string peopleFieldName )
    {
        //Make call to the proper repo method.
        return Json(_peopleFieldRepo.C_Update(peopleFieldID, peopleFieldName));
    }
Run Code Online (Sandbox Code Playgroud)

peopleFieldID 和 peopleFieldName 这两个参数始终为 0 和 null。我已经指出 Angular 前端正确发送了参数,但后端无法识别它们。我有许多其他端点可以正常工作。

asp.net-web-api asp.net-core angular angular-httpclient

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

Angular HttpClient无法正确反序列化Scala类

我有以下traitclassesScala

sealed trait Algorithm {
  val name: String
  val formula: String
  val parameters: Seq[AlgorithmParameter[Any]]

  def enhanceAlgorithm[T](algorithm: T): Unit
}

case class LinearRegressionAlgorithm(override val name: String, override val formula: String) extends Algorithm {}
case class GeneralizedLinearRegressionAlgorithm(override val name: String, override val formula: String) extends Algorithm {}


sealed abstract class AlgorithmParameter[+T](val name: String, val value: T, val selectOptions: Seq[T]) extends EnumEntry

object AlgorithmParameter extends Enum[AlgorithmParameter[AnyVal]] with CirceEnum[AlgorithmParameter[AnyVal]] {

  case object MaxIter extends AlgorithmParameter[Int]("maxIter", 100, Seq())

} …
Run Code Online (Sandbox Code Playgroud)

scala traits typescript angular angular-httpclient

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

HttpClient返回一次json,然后返回undefined

我正在使用从服务器读取JSON的内容HttpClient。我能够成功读取一次内容,但是当我第二次读取它时,它总是返回undefined

这是我的.ts样子:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  constructor(private httpService: HttpClient) { }

  getData() {
    this.httpService.get('https://raw.githubusercontent.com/LearnWebCode/json-example/master/animals-1.json').subscribe(
          result => { 
            console.log(result)
          }
    )
  }

   ngOnInit() {
     this.getData()
     setInterval(this.getData, 10000)
   }
}
Run Code Online (Sandbox Code Playgroud)

HttpClientapp.module.ts在我第一次阅读JSON时已正确导入,它可以正常工作。

这是有问题的stackBlitz

我正在使用,setInterval因为我希望能够继续读取JSON,因为值将更新。我是否打算关闭httpClient.get请求,以便我可以提出另一个请求。

我看到了其他问题,其中请求始终返回,undefined而我的请求仅undefined在第二个请求之后返回。

每次发送get请求时,如何成功获取JSON的内容?

编辑 显然,对于我的某些stackblitz来说,这不是问题,这是来自控制台的stackblitz的屏幕截图,其中包含以下问题:
在此处输入图片说明

json angular angular-httpclient

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