Angular文档说:
响应正文不会返回您可能需要的所有数据.有时,服务器返回特殊标题或状态代码以指示某些条件,并且检查这些条件是必要的.要做到这一点,你可以告诉HttpClient你想要完整的响应,而不仅仅是带有observe选项的body:
http
.get<MyJsonData>('/data.json', {observe: 'response'})
.subscribe(resp => {
// Here, resp is of type HttpResponse<MyJsonData>.
// You can inspect its headers:
console.log(resp.headers.get('X-Custom-Header'));
// And access the body directly, which is typed as MyJsonData as requested.
console.log(resp.body.someField);
});
Run Code Online (Sandbox Code Playgroud)
但是当我尝试这个时,我得到一个编译时错误(尽管没有运行时错误,按预期工作):
错误TS2345:类型'{headers:HttpHeaders; 观察:字符串; ''不能赋值给'{headers?:HttpHeaders |'类型的参数 {[header:string]:string | 串[]; }; 观察?:"身体"; params?:Ht ......'.财产'观察'的类型是不相容的.类型'string'不能分配给''body''.
为什么?我用"@angular/http": "^5.1.0"
这是我的代码版本:
login(credentials: Credentials): Observable<any> {
const options = {
headers: new HttpHeaders({'Content-Type': 'application/json'}),
observe: 'response'
};
return this.httpClient.post<any>(`${environment.USER_SERVICE_BASE_URL}`,
{'username': credentials.username, 'password': credentials.password}, options)
.map((res) => ...
Run Code Online (Sandbox Code Playgroud) 两个http调用完成后,我使用Observable.forkJoin()来处理响应,但如果其中任何一个返回错误,我怎么能捕获该错误?
Observable.forkJoin(
this.http.post<any[]>(URL, jsonBody1, postJson) .map((res) => res),
this.http.post<any[]>(URL, jsonBody2, postJson) .map((res) => res)
)
.subscribe(res => this.handleResponse(res))
Run Code Online (Sandbox Code Playgroud) 使用 Typescript/Angular 9:
const formData: FormData = new FormData();
formData.append('key', null);
console.log(formData.get('key'));
>> 'null'
Run Code Online (Sandbox Code Playgroud)
这是一个“空”字符串,而不是null值。
我需要以某种方式将 null(或未定义)值附加到FormData. 我能做些什么?
我正在调用一个返回JSON对象的API.我只需要数组的值来映射到Observable.如果我调用api只返回数组我的服务调用工作.
以下是我的示例代码..
// my service call ..
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Show} from '../models/show';
import {HttpClient} from '@angular/common/http';
@Injectable()
export class MyService {
constructor(private http: HttpClient ) { }
findAllShows(): Observable<Show[]> {
return this.http
.get<Show[]>(`${someURL}/shows`)
}
}
Run Code Online (Sandbox Code Playgroud)
如果返回的是JSON对象,如下面的那个失败..
// Service API that FAILS ...
{
"shows": [
{
"id": "123f9165-80a2-41d8-997a-aecc0bfb2e22",
"modified": "2017-08-13 15:54:47",
"name": "Main Show1"
},
{
"id": "456f9165-80a2-41d8-997a-aecc0bfb2e22",
"modified": "2017-08-14 15:54:47",
"name": "Main Show2"
},
{
"id": "789f9165-80a2-41d8-997a-aecc0bfb2e22",
"modified": "2017-08-17 15:54:47", …Run Code Online (Sandbox Code Playgroud) 对于学校项目,我需要使用Angular创建一个简单的登录页面.单击登录按钮时,我需要在帖子中添加Authorization标头.我创建了一个后端,当我使用邮递员将我的授权值发布到该后端时,它的工作方式与后端没有任何问题.当我尝试使用我的前端发布到同一个后端时,它不起作用.向帖子添加标题的最佳方法是什么?似乎意见分歧.这是我的代码:
export class LoginComponent{
title = 'Login';
email = '';
password = '';
credentials = '';
basic = '';
constructor(private http:HttpClient){
}
createAuthorizationHeader(headers:Headers,basic){
headers.append('Authorization',basic);
}
login(event){
this.email = (<HTMLInputElement>document.getElementById("email")).value;
this.password = (<HTMLInputElement>document.getElementById("password")).value;
this.credentials = this.email + ":" + this.password;
this.basic = "Basic " + btoa(this.credentials);
console.log(this.basic);
let headers = new Headers();
headers.append('Content-Type','application/json');
headers.append('Authorization',this.basic);
let options = new RequestOptions({headers:headers});
console.log(headers);
return this.http.post('http://localhost:8000/api/v1/authenticate',options)
.subscribe(
res =>{
console.log(res);
},
err => {
console.log(err.message);
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行该代码时,我得到400状态响应并且不添加标头.
上下文:我正在尝试从后端下载二进制文件(需要将一些数据发布为json-body),并使用内容处置标头中后端指定的文件名保存文件保护程序.要访问标题,我想我需要HttpResponse.
但是我无法使用HttpClient.post<T>(...): Observable<HttpResponse<T>>;带有Blob的angular 方法.
我打电话的时候
this.httpclient.post<Blob>('MyBackendUrl',
params,
{observe: 'response', responseType: 'blob'});
the compiler complains about the 'blob' ('json' is accepted by the compiler):
error TS2345: Argument of type '{ observe: "response"; responseType: "blob"; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
Types of property 'observe' are incompatible.
Type '"response"' is not assignable to type '"body"'.
Run Code Online (Sandbox Code Playgroud)
当我把选项放在一个自己的对象中,如/sf/answers/3361165671/所示(但没有"as"...)帖子(...):Observable被调用,我不能访问标题.
顺便说一句,即使是return this.http.get<Blob>('backendUrl', {responseType: 'blob'}); …
/* error handler that will be used below in pipe with catchError()
* when resource fetched with HttpClient get() */
private _handleError<T> (operation: string, result?:T) {
return( error: any): Observable<T> => {
console.error( operation + ' ' + error.message );
// or something else I want to do
return of(result as T); // lets me return innocuous results
}
}
getObjects() {
return this.http.get<any[]>(this.myUrl).pipe(
catchError(this._handleError('my error', [])
);
}
Run Code Online (Sandbox Code Playgroud)
现在tap用于处理错误
getObjects() {
return this.http.get<any[]>(this.myUrl).pipe(
tap( objects => { …Run Code Online (Sandbox Code Playgroud) 我有一个auth-interceptor.service.ts处理请求
import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Cookie} from './cookie.service';
import {Router} from '@angular/router';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private router: Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set(Cookie.tokenKey, Cookie.getToken())});
// Pass on the cloned request instead of the original request.
return next.handle(authReq).catch(this.handleError);
}
private handleError(err: HttpErrorResponse): Observable<any> {
console.log(err);
if …Run Code Online (Sandbox Code Playgroud) typescript angular-http angular-http-interceptors angular angular-httpclient
我想用拦截器排除一些服务.
app.module.js
providers: [
UserService,
RolesService,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
},
],
Run Code Online (Sandbox Code Playgroud)
Login.service.ts
return this.httpClient.post(this.appUrl + '/oauth/token', body.toString(), { headers, observe: 'response' })
.map((res: Response) => {
const response = res.body;
this.storeToken(response);
return response;
})
.catch((error: any) => {
ErrorLogService.logError(error);
return Observable.throw(new Error(error.status));
});
}
Run Code Online (Sandbox Code Playgroud) 我在我的 Angular 应用程序中创建了一个 REST API 调用来下载一个文件。
我将 responseType 设置为 'blob' 因为我期待一个文件作为响应。
但是当服务器上没有可用的文件时,响应的错误代码为 404,即错误请求,正文中有一些消息。
但是我无法解析来自正文的错误消息,因为 HttpErrorResponse 在 error.error 中给出了一个 blob 对象
如何从错误对象而不是 blob 中获取实际主体。
还有什么方法可以配置 angular,在 api 调用成功时解析 blob 中的请求,否则解析 json 中的请求???
希望得到解决
angular ×9
rxjs ×3
typescript ×3
angular-http ×2
arrays ×1
interceptor ×1
javascript ×1
json ×1
promise ×1