【问题标题】:Httpclient angular tutorialHttpclient 角度教程
【发布时间】:2018-03-20 08:50:58
【问题描述】:

我已按照 Angular 网站 (https://angular.io/guide/http) 上的教程进行操作,但我无法实现我想要的,因为我有一个我不明白的错误。 我已将我的文本文件放在资产文档中,并创建了一个 config.json 文件,我在其中输入了教程中的代码。 我的 service.ts 文件和 component.ts 文件也出现错误。 请帮助我理解我的错误和教程。

Component.ts

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {HttpClient, HttpErrorResponse, HttpResponse} from '@angular/common/http';
import {GeneralService} from '../general.service';

@Component({
  selector: 'app-general',
  templateUrl: './general.component.html',
  styleUrls: ['./general.component.css']
})
 export interface General {
  generalUrl: string;
  textfile: string;
}
 export class GeneralComponent implements OnInit {
  title = 'Introduction';
  generalUrl = 'assets/project_description.txt';
  general: General;
  generalService: GeneralService;

 constructor(private http: HttpClient) { }

 ngOnInit() {
}

 getGeneral() {
  return this.http.get(this.generalUrl);
}

 showGeneral() {
  this.generalService.getGeneral()
   .subscribe(data => this.general = {
     generalUrl: data['generalUrl'],
     textfile: data['textfile']
   });
}

showGeneralResponse() {
 this.generalService.getGeneralResponse()
  .subscribe(resp => {
    const keys = resp.headers.keys();
    this.headers = keys.map(key =>
    `${key}: ${resp.headers.get(key)}`);
  this.config = {
  });
 }
}

在我的 showGeneralResponse() 函数头和配置中是未解析的变量

Service.ts

import { Injectable } from '@angular/core';
import {General} from './general/general.component';
import {HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class GeneralService {

  constructor() { }
  getGeneral() {
    return this.http.get<General>(this.generalUrl);
  }
  getGeneralResponse(): Observable<HttpResponse<General>> {
    return this.http.get<General>(
      this.generalUrl, { observe: 'response'}
    );
  }
}

在 getGeneral() 和 getGeneralresponse() 函数中,我有 http 和 generalUrl 是未解析的变量

但是在我的 config.json 文件中我没有错误

config.json

 "generalUrl": "api/general",
 "textfile": "assets/project_description.txt"

我也想知道在我的 html 文件中放入哪个函数,以便我的应用程序显示我的文件文本

【问题讨论】:

  • 请告诉我你的错误
  • 你想用 HttpClient 读取 config.json 数据吗?
  • 在我的 showGeneralResponse() 函数中 -> showGeneralResponse() { this.generalService.getGeneralResponse() .subscribe(resp =&gt; { const keys = resp.headers.keys(); this.**headers** = keys.map(key =&gt; ${key}: ${resp.headers.get(key)}); **this.general** = { }); } 错误在 headers 中,它说它是一个未解决的变量而且我不知道该放什么this.general 的括号
  • @LucieSchaffner 我们不需要您重新格式化错误,我们需要的只是错误跟踪。你能把它贴在你的问题中吗?并且是全文,请不要作为图片
  • 请像这样更改 getGeneral 方法:getGeneral() { return this.http.get(this.generalUrl).map((res: Response) =&gt; res.json()); }

标签: angular typescript httpclient


【解决方案1】:

Lucie,我很着急,(我想问题是 Angular 找不到文件 data.json)。我举了一个我知道的更简单的例子:

//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [DataService,],
  bootstrap: [AppComponent]
})
export class AppModule { }

//DataService.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class DataService {
    constructor(private http: HttpClient) { }
    getData() {
        return this.http.get('../assets/data.json')
    }
}
//app.compontent.ts
import { Component, OnInit } from '@angular/core';
import {DataService} from './data.service'
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  data:any;
  constructor(private dataService:DataService){}
  ngOnInit(){
    this.dataService.getDataDos(null).subscribe(res=>{
        this.data=res;
    })
  }
  }
}

//app.component.html
{{data |json}}

//data.json (in folder assets/)
[
    {"key":"uno"},
    {"key":"dos"},
    {"key":"tres"},
    {"key":"cuatro"},
    {"key":"cinco"}
]

【讨论】:

  • 非常感谢您帮了我很多忙!我发现我的错误,我没有在 app.module.ts 中导入 HttpModule 而是 HttpClient
【解决方案2】:

@露西·沙夫纳 1.- json 必须是 json,见 "{" 和 "

{
    generalUrl: "api/general",
    textfile: "assets/project_description.txt"
}

2.-您在组件中定义了变量“generalUrl”,但在服务中没有。

3.-如果要在组件中使用Service,必须在构造函数中注入

//In your component

//remove the line below
//generalService: GeneralService;

//And change the cosntructor
constructor(private http: HttpClient,private generalService:GeneralService) { }

4.-你必须在你的 ngOnInit() 中调用函数 this.showGeneral() 否则永远不会发生

5.- 在组件之前声明导出接口

import { Component, OnInit } from '@angular/core';
...
//Move export inferface here
 export interface General {
  generalUrl: string;
  textfile: string;
}

@Component({
  selector: 'app-general',
  templateUrl: './general.component.html',
  styleUrls: ['./general.component.css']
})
 export class GeneralComponent implements OnInit {
...
}

【讨论】:

  • 帮助很大,我纠正了一些错误,我可以更好地理解我的错误,但我仍然不知道如何处理我的 showGeneralResponse() 函数,所以我评论了它,我得到这个错误:ERROR in src/app/general/general.component.ts(6,1): error TS1206: Decorators are not valid here.
  • @Lucie,您必须在 @ 组件之前声明“接口”(我更新了我的答案)
  • 非常感谢它修复了错误但是我怎样才能让我的文本文件现在在我的应用程序上显示呢?我应该如何在我的html中声明它以及哪个函数?
  • 你有一个变量 this.generalData。如果在你的 general.component.html 你写 {{generalData.generalUrl}}{{generalData.textfile}} 你可以看到变量的值。
  • 我已经完成了你告诉我的所有事情,它编译得很好,没有错误,但它什么也没有显示,甚至是一个简单的&lt;h1&gt; Hello &lt;h1&gt; 我找不到我的错误我已经通过我的代码几次,甚至重新创建了一个新项目
【解决方案3】:

有一个库允许您将 HttpClient 与强类型回调一起使用

数据和错误可直接通过这些回调获得。

当您将 HttpClient 与 Observable 一起使用时,您必须在其余代码中使用 .subscribe(x=>...)

这是因为 ObservableHttpResponseT>>HttpResponse 绑定。

http层您的代码的其余部分紧密结合

这个库封装了 .subscribe(x => ...) 部分,只通过你的模型暴露数据和错误。

使用强类型回调,您只需在其余代码中处理模型。

该库名为 angular-extended-http-client

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

非常容易使用。

示例用法

强类型回调是

成功:

  • IObservableT>
  • IObservableHttpResponse
  • IObservableHttpCustomResponseT>

失败:

  • IObservableErrorTError>
  • IObservableHttpError
  • IObservableHttpCustomErrorTError>

将包添加到您的项目和应用模块中

import { HttpClientExtModule } from 'angular-extended-http-client';

在@NgModule 导入中

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

你的模型

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

您的服务

在您的服务中,您只需使用这些回调类型创建参数。

然后,将它们传递给 HttpClientExt 的 get 方法。

import { Injectable, Inject } from '@angular/core'
import { RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    getRaceInfo(success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.get(url, ResponseType.IObservable, success, ErrorType.IObservableError, failure);
    }
}

你的组件

在您的组件中,您的服务被注入并调用 getRaceInfo API,如下所示。

  ngOnInit() {    
    this.service.getRaceInfo(response => this.result = response.result,
                                error => this.errorMsg = error.className);

  }

回调中返回的 responseerror 都是强类型的。例如。 responseRacingResponse 类型,errorAPIException

您只在这些强类型回调中处理您的模型。

因此,您的其余代码只知道您的模型。

另外,您仍然可以使用传统路由并从 Service API 返回 ObservableHttpResponse<T&gt;>。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    相关资源
    最近更新 更多