在这篇文章中,我们将带领您了解Angular2:无法访问http请求中的响应标头的全貌,包括angular无法加载路由的相关情况。同时,我们还将为您介绍有关Angular2Http请求不发送凭据、An
在这篇文章中,我们将带领您了解Angular 2:无法访问http请求中的响应标头的全貌,包括angular无法加载路由的相关情况。同时,我们还将为您介绍有关Angular 2 Http请求不发送凭据、Angular 4.3 HttpClient (Angular访问 REST Web 服务) 一、Http 请求示例(Get)、Angular 4.3 HttpClient (Angular访问 REST Web 服务) 二、Http 请求结果类型转换与错误处理、Angular 4中的并行HTTP请求的知识,以帮助您更好地理解这个主题。
本文目录一览:- Angular 2:无法访问http请求中的响应标头(angular无法加载路由)
- Angular 2 Http请求不发送凭据
- Angular 4.3 HttpClient (Angular访问 REST Web 服务) 一、Http 请求示例(Get)
- Angular 4.3 HttpClient (Angular访问 REST Web 服务) 二、Http 请求结果类型转换与错误处理
- Angular 4中的并行HTTP请求
Angular 2:无法访问http请求中的响应标头(angular无法加载路由)
var req = new Request({ url: `localhost/api/products`,method: RequestMethods.Get }); this.http.request(req).subscribe( res => { // Can't access the headers of the response here.... res.headers is empty },error => { ... },_ => {} );
奇怪的是,如果我在浏览器的开发工具中检查网络流量,则会出现响应头…
解决方法
https://github.com/angular/angular/issues/5237#issuecomment-156059284
请检查一下,因为有人发布了一个解决方法.
UPDATE
棱角分明的团队已经解决了这个问题.
Angular 2 Http请求不发送凭据
这个Angular 1代码运行良好,它包含凭据:
$http.get("http://some.com/user",{ withCredentials: true})
根据API预览,我已经实现了这个Angular 2代码,但它不包含凭据:
http.get("http://some.com/user",{ headers: myHeaders,credentials: RequestCredentialsOpts.Include }).toRx() .map(res => res.json()) .subscribe( // onNext callback data => this.successHandler(data),// onError callback err => this.failure(err) );
我正在使用Angular 2.0.0-alpha.37.
解决方法
如果在xhr_backed.js中添加代码,则可以将“凭据”发送到服务器
this._xhr.withCredentials = true;
angular2@2.0.0-alpha.37/src/http/backends/xhr_backed.js
var XHRConnection = (function() { function XHRConnection(req,browserXHR,baseResponSEOptions) { ........ this._xhr = browserXHR.build(); this._xhr.withCredentials = true; ........
总结
以上是小编为你收集整理的Angular 2 Http请求不发送凭据全部内容。
如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。
Angular 4.3 HttpClient (Angular访问 REST Web 服务) 一、Http 请求示例(Get)
链接
开发工具:Visual Studio Code
在Angular 4.3中引入了新的HttpClientModule。 这个新模块可以在@ angular / common / Http包中找到,并且可以完全重新实现前一个HttpModule。新的HttpClient服务包含在HttpClientModule中,可用于启动HTTP请求并处理应用程序中的响应。
安装 4.3 项目
开始Angular 4.3项目第一步。最简单的是用Angular CLI (Angular command line interface).
- 如果系统还没有安装过Angular CLI ,先要执行下面的命令安装最新版(-g:全局安装):
npm install -g @angular/cli@latest
如果有安装cnpm,可用cnpm,下载速度更快
cnpm install -g @angular/cli@latest
- 新建一个文件夹ng_http,用来存放项目。命令行切换到此目录,然后用VS Code打开。
cd D:\Angular\NG_App
code .
- 接着,就可以使用 ng命令了开始一个新的Angular 项目了:
ng new nghttp01
如果报错,并在错误日志记录总显示
integrity checksum Failed when using sha512
npm4升级npm5,在运行 npm install 时,可能会包这样的错误,执行
npm cache clean --force
删除项目文件夹,重新执行。
ng new nghttp01
执行成功后会产生 nghttp01文件夹与项目模板,依赖性也会自动安装。 - 检查并确认 package.json 中Angular相关所有依赖版本 号 >4.3.0。
- package.json 文件做过更新后,命令行中切换到nghttp01下,执行下面命令更新
npm install
在项目中启用 HttpClient
1。为了在项目components 中使用 HttpClient 服务,第一步就是要在Angular应用中把 HttpClientModule 包含进来。首先在应用根module中导入 HttpClient module,对应文件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: [],bootstrap: [AppComponent] })
2。上一步在根 Module 导入了HttpClientModule ,就可以在components中使用HttpClient了。使用HttpClient第一步是导入(import),还必须要注入(inject )到component class的构造函数中。如下所示:
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http';//新增行 @Component({ selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; constructor(private http: HttpClient){//新增行,httpclient注入到构造函数中,以使HttpClient可用。 } }
3。HttpClient使用XMLHttpRequest浏览器API来执行HTTP请求。 为了执行特定类型的HTTP请求,可以使用以下与HTTP动词相对应的方法:
**get
post
put
delete
patch
head
jsonP**
使用HttpClient 请求数据
1。 简单示例:使用 GitHub’s REST API 请求用户数据。修改app.component.ts代码(完整):
import { Component,OnInit } from '@angular/core';//新增导入OnInit import { HttpClient } from '@angular/common/http';//新增行 @Component({ selector: 'app-root',styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit {//新增implements OnInit title = 'app'; results = ''; constructor(private http: HttpClient){///新增行,httpclient注入到构造函数中,以使HttpClient可用。 } //新增ngOnInit()方法 ngOnInit(): void { this.http.get('https://api.github.com/users/seeschweiler').subscribe(data => { console.log(data); }); } }
2。项目启动:VS Code命令行执行。网页访问http://localhost:4200/
ng serve
Angular 4.3 HttpClient (Angular访问 REST Web 服务) 二、Http 请求结果类型转换与错误处理
Http Get响应(Response)类型转换
接着上一节。
1。在浏览器控制台中可以看到响应的JSON对象有许多属性(properties)。如果试着用data.login访问login属性会报错。
console.log(data.login);
因为Get返回的是Object类型。
Angular get原型
typescript
get(url: string,options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<Object>;
2。转换响应的object对象为自定义对象:
2.1 自定义类型UserResponse :
import { Component,OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'app'; results = ''; constructor(private http: HttpClient){ } ngOnInit(): void { this.http.get<UserResponse>('https://api.github.com/users/seeschweiler').subscribe(data => { //console.log(data); console.log("User Login: " + data.login); console.log("Bio: " + data.bio); console.log("Company: " + data.company); }); } } interface UserResponse { login: string; bio: string; company: string; }
错误处理
1。由于一些可预见或不可预见的状况,会导致 HTTP失败。因此应该总是有处理这些错误状况的代码存在。 Get的subscribe方法有两个参数 未回调函数,用于处理Get成功与失败的情况。
subscribe方法原型
subscribe(next?: (value: T) => void,error?: (error: any) => void,complete?: () => void): Subscription;
失败处理
this.http.get<UserResponse>('https://api.github.com/users/seeschweiler').subscribe( data => { console.log("User Login: " + data.login); console.log("Bio: " + data.bio); console.log("Company: " + data.company); },//新增失败处理 err => { console.log("Error occured.") } );
2。失败详细信息:错误处理回调函数参数类型是any,可将其转换为HttpErrorResponse类型,并可获取更多错误属性信息。 HttpErrorResponse 需要从@angular/common/http导入才能使用。
完整app.component.ts
import { Component,OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import {HttpErrorResponse} from '@angular/common/http'; @Component({ selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'app'; results = ''; constructor(private http: HttpClient){ } ngOnInit(): void { this.http.get<UserResponse>('https://api.github.com/users/seeschweiler').subscribe(data => { console.log(data); console.log("User Login: " + data.login); console.log("Bio: " + data.bio); console.log("Company: " + data.company); },(err: HttpErrorResponse) => { if (err.error instanceof Error) { console.log("Client-side error occured."); } else { console.log("Server-side error occured."); } } ); } } interface UserResponse { login: string; bio: string; company: string; }
Angular 4中的并行HTTP请求
仪表板页面应显示用户指定的~5个城市的当前天气.
所以我的问题是 – 给定一个由5个城市组成的数组,对于该数组中的每个元素,为REST服务(通过Angular服务)发出调用的最佳方法是什么.
这是我最初尝试的代码摘录:
locations: string[] = ["Seattle","Woodinville","Krasnoyarsk","Stockholm","Beijing"]; ... ngOnInit() { this.locations.forEach(function(element) { this.weatherService.getWeather(element).subscribe((data) => { console.log(data); }); }); }
但这会产生错误:
编译失败.
c:/Projects/weather-app/src/app/components/dashboard/dashboard.component.ts(19,12):’void’类型中不存在属性’weatherService’.
我意识到’forEach’在这里不起作用 – 但是在ng 4中这样做的最佳做法是什么?
谢谢.
解决方法
当所有响应都到位时,forkJoin将发出值
Observable .forkJoin(this.locations .map((element) => this.weatherService.getWeather(element)) .subscribe((data) => console.log(data));
今天关于Angular 2:无法访问http请求中的响应标头和angular无法加载路由的讲解已经结束,谢谢您的阅读,如果想了解更多关于Angular 2 Http请求不发送凭据、Angular 4.3 HttpClient (Angular访问 REST Web 服务) 一、Http 请求示例(Get)、Angular 4.3 HttpClient (Angular访问 REST Web 服务) 二、Http 请求结果类型转换与错误处理、Angular 4中的并行HTTP请求的相关知识,请在本站搜索。
本文标签: