我需要上传一个文件并发送一些json,我有这个功能:
POST_formData(url, data) {
var headers = new Headers(), authtoken = localStorage.getItem('authtoken');
if (authtoken) {
headers.append("Authorization", 'Token ' + authtoken)
}
headers.append("Accept", 'application/json');
headers.delete("Content-Type");
var requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: this.apiURL + url,
headers: headers,
body: data
})
return this.http.request(new Request(requestoptions))
.map((res: Response) => {
if (res) {
return { status: res.status, json: res.json() }
}
})
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果我设置content-type为" multipart/form-data"我的服务器抱怨边界,如果我content-type完全删除标头,我的服务器抱怨它" text/plain"支持的媒体类型.
那么,如何使用angular2发送FormData?
我有一个使用Angular 2的Ionic 2应用程序,它将Http PUT发送到ASP.NET Core API服务器.这是我用来发送请求的方法:
public update(student: Student): Promise<Student>
{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `${student.token}`);
const url = `${this.studentsUrl}`;
return this.http
.put(url, JSON.stringify(student), { headers: headers })
.toPromise()
.then(() => student)
.catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
我在headers对象上设置了身份验证密钥/值.
但是当我在服务器上收到此请求时,我在标题上找不到身份验证密钥:
正如您在图片中看到的那样,标题上有许多键,但不是我手动添加到客户端应用程序中的标题的内容和身份验证密钥.
我究竟做错了什么?
我遵循这个教程.在从api.github获取用户列表的途中我得到错误:
找不到支持对象'[object Object]'
我认为它与之相关
<ul>
<li *ngFor = "#user of users">
{{user | json}}
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
在我的代码中,因为在它之前没有任何错误,并且我不确定数据是否来自get请求,只是单击didnt没有给出任何错误,这是我的代码到目前为止
@Component({
selector: 'router',
pipes : [],
template: `
<div>
<form [ngFormModel] = "searchform">
<input type = 'text' [ngFormControl]= 'input1'/>
</form>
<button (click) = "getusers()">Submit</button>
</div>
<div>
<ul>
<li *ngFor = "#user of users">
{{user | json}}
</li>
</ul>
</div>
<router-outlet></router-outlet>
`,
directives: [FORM_DIRECTIVES]
})
export class router {
searchform: ControlGroup;
users: Array<Object>[];
input1: AbstractControl;
constructor(public http: Http, fb: FormBuilder) {
this.searchform …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用withCredentials将cookie发送到我的服务但无法找到如何实现它.文档说"如果服务器需要用户凭据,我们将在请求标头中启用它们"没有示例.我尝试了几种不同的方法,但它仍然不会发送我的cookie.到目前为止,这是我的代码.
private systemConnect(token) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('X-CSRF-Token', token.token);
let options = new RequestOptions({ headers: headers });
this.http.post(this.connectUrl, { withCredentials: true }, options).map(res => res.json())
.subscribe(uid => {
console.log(uid);
});
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试通过Angular2浏览英雄应用程序,并在本教程的Http部分遇到错误.
起初我得到了错误:
Cannot find module 'angular2-in-memory-web-api'
Run Code Online (Sandbox Code Playgroud)
但是,在同一步骤中我也遇到以下错误:
app/app.module.ts(10,38): error TS2307: Cannot find module './in-memory-data-service'.
Run Code Online (Sandbox Code Playgroud)
我已经三次检查了,我相信我的in-memory-data-service.ts文件和我的app.module.ts文件与教程中列出的完全相同(在这个特定的时间点).
现在我的in-memory-data-service.ts文件如下所示:
码:
import { InMemoryDbService } from 'angular2-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
let heroes = [
{id: 11, name: 'Mr. Nice'},
{id: 12, name: 'Narco'},
{id: 13, name: 'Bombasto'},
{id: 14, name: 'Celeritas'},
{id: 15, name: 'Magneta'},
{id: 16, name: 'RubberMan'},
{id: 17, name: 'Dynama'},
{id: 18, name: 'Dr IQ'}, …Run Code Online (Sandbox Code Playgroud) 我正在开发一个Angular 2应用程序,需要一些关于如何干净地处理身份验证错误的指导.
我的最终目标是能够集中处理每个Http请求的身份验证错误(特别是401和403).
我发现这个问题对于让我开始非常有帮助,但是我仍然坚持为我的自定义Http实现返回的每个observable注册我的错误处理程序的正确方法.
以下是我目前正在使用的示例:
import { Injectable } from 'angular2/core';
import { Http, ConnectionBackend, Request, RequestOptions, RequestOptionsArgs, Response } from 'angular2/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class ClauthHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
get(url: string, options ? : RequestOptionsArgs): Observable < Response > {
var response = super.get(url, options);
return this._handleSecurityResponse(response);
}
/*
Other overrides omitted for brevity...
*/
private _handleSecurityResponse(response: Observable < Response …Run Code Online (Sandbox Code Playgroud) 我正在为angular2服务编写单元测试.代码片段:
// jasmine specfile
// already injected MockConnection into Http
backend.connections.subscribe ((c: MockConnection) => {
connection = c;
});
// doing get-request
myServiceCallwithHttpRequest ().subscribe (result => {
// this test passes!
expect (result).toEqual ({
"message": "No Such Object"
});
// this test fails, don't know how to get the response code
expect (whereIsResponseStatus).toBe (404);
});
connection.mockRespond (new Response (new ResponseOptions ({
body: {
"message": "No Such Object"
},
status: 404
})));
Run Code Online (Sandbox Code Playgroud)
我的服务:
// service
myServiceCallwithHttpRequest (): Observable<Response> {
return this.http.get …Run Code Online (Sandbox Code Playgroud) 我想复制一个REST响应成团块,但我不能做一些,因为blob()和arrayBuffer()尚未响应对象已经实施.Response Body是一个私有变量.
...
return this.http.get(url, {params: params, headers: headers})
.map(res => {
// can't access _body because it is private
// no method appears to exist to get to the _body without modification
new Blob([res._body], {type: res.headers.get('Content-Type')});
})
.catch(this.log);
...
Run Code Online (Sandbox Code Playgroud)
在实施这些方法之前,我是否可以使用解决方案?
通过URLSearchParams的Angular文档,我找到了关于将数组作为参数传递的任何文档.
任何人都可以帮忙吗?
我理解使用observable我可以在请求完成时执行一个方法,但是我怎么能等到http get完成并使用ng2 http返回响应?
getAllUser(): Array<UserDTO> {
this.value = new Array<UserDTO>();
this.http.get("MY_URL")
.map(res => res.json())
.subscribe(
data => this.value = data,
err => console.log(err),
() => console.log("Completed")
);
return this.value;
}
Run Code Online (Sandbox Code Playgroud)
返回时,"value"将为null,因为get是异步的..
angular ×10
angular2-http ×10
typescript ×4
javascript ×2
blob ×1
file-upload ×1
http ×1
httpresponse ×1
rest ×1
rxjs ×1
unit-testing ×1