我正在使用EXCEPTION: No provider for Http!我的Angular应用程序.我究竟做错了什么?
import {Http, Headers} from 'angular2/http';
import {Injectable} from 'angular2/core'
@Component({
selector: 'greetings-ac-app2',
providers: [],
templateUrl: 'app/greetings-ac2.html',
directives: [NgFor, NgModel, NgIf, FORM_DIRECTIVES],
pipes: []
})
export class GreetingsAcApp2 {
private str:any;
constructor(http: Http) {
this.str = {str:'test'};
http.post('http://localhost:18937/account/registeruiduser/',
JSON.stringify(this.str),
{
headers: new Headers({
'Content-Type': 'application/json'
})
});
Run Code Online (Sandbox Code Playgroud) 我正在尝试发出POST请求,但我无法让它工作:
testRequest() {
var body = 'username=myusername?password=mypassword';
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http
.post('/api',
body, {
headers: headers
})
.subscribe(data => {
alert('ok');
}, error => {
console.log(JSON.stringify(error.json()));
});
}
Run Code Online (Sandbox Code Playgroud)
我基本上想要复制这个http请求(不是ajax),就像它是由html表单生成的:
网址:/ api
参数:用户名和密码
现在,我做http请求的方式(借用这个答案)是这样的:
POST(url, data) {
var headers = new Headers(), authtoken = localStorage.getItem('authtoken');
headers.append("Content-Type", 'application/json');
if (authtoken) {
headers.append("Authorization", 'Token ' + authtoken)
}
headers.append("Accept", 'application/json');
var requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: this.apiURL + url,
headers: headers,
body: JSON.stringify(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)
这样可以正常工作,除非如果返回的状态代码不是200,angular2将失败.例如,如果用户想要发布某些东西而服务器返回400,则角度2将抛出异常:
未捕获的异常:[object Object]
我怎么能避免这个?我想在我的应用中处理这些状态代码,以增强用户体验(显示错误等)
我不明白我做错了什么,当我尝试获取json时,我的服务器返回"undefined".
POST(url, data) {
var headers = new Headers(), authtoken = localStorage.getItem('authtoken');
headers.append("Content-Type", 'application/json');
if (authtoken) {
headers.append("Authorization", 'Token ' + authtoken)
}
headers.append("Accept", 'application/json');
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)
我的功能:
login(username, password) {
this.POST('login/', {test: 'test'}).subscribe(data => {
console.log(data)
})
}
Run Code Online (Sandbox Code Playgroud)
当我尝试这个时,请求体看起来像这样:
因此,它不是发送实际的json,而是发送"[object Object]".它不应该是"请求有效载荷",而应该是"JSON".我究竟做错了什么?
如何在angular2中设置Content-Type和Accept?
我试图在标题中发送内容类型(application/json)的帖子调用但是因为某些原因它不发送,它总是发送text/plain; charset =内容类型中的UTF-8当我尝试进行REST服务调用时,我得到415不支持的媒体类型.我认为我需要正确地设置类型和内容类型它不会从代码设置我 在我们下面的标头请求
Accept
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Content-Length
13
Content-Type
text/plain; charset=UTF-8
Host
enrova.debug-zone.com:8000
Origin
http://localhost:8000
Referer
http://localhost:8000/add
User-Agent
Mozilla/5.0 (Windows NT 10.0; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Run Code Online (Sandbox Code Playgroud)
代码如下
import {Component, View} from 'angular2/angular2';
import { Inject} from 'angular2/di';
import {Http} from 'angular2/http';
export class AchievementsService {
constructor( @Inject(Http) private http: Http) {
}
getAchievementsOfType(type: string) : any {
var path = '/api/achievements/' + type;
return this.http.get(path);
}
getAllAchievements() : any {
var path = '/api/achievements'; …Run Code Online (Sandbox Code Playgroud) 我尝试将Authorization标头设置为GET请求,以将用户身份验证为其他API.我正在使用Angular 2 RC1.(我是初学者).
getTest(){
let authToken = localStorage.getItem('auth_token');
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Authorization', `Bearer ${authToken}`);
let options = new RequestOptions({ headers: headers });
return this._http
.get(this._url,options)
.map(res => console.log(res));
}
Run Code Online (Sandbox Code Playgroud)
我在后端允许CORS.
header("Access-Control-Allow-Origin: *");
header("Access-Control-Request-Headers: Content-Type, Authorization");
Run Code Online (Sandbox Code Playgroud)
我的控制台:
选项api/userProfile /
XMLHttpRequest无法加载/ userProfile /.预检的响应具有无效的HTTP状态代码406
任何的想法 ?
我是Angular2的新手.我想在我的MVC6项目中使用Angular2调用API.我已经尝试了很多东西(包括Angular2调用ASP.NET Web API的指南)但没有成功.
我不知道应该从哪里开始,或者需要哪些文件.
我有一个组件,首先需要调用POST的服务.然后在同一个组件中我想等到POST完成后,调用另一个获取数据的服务.
如何进行GET调用等待POST调用完成?
在new-version.component.ts中:
private createNewVersion(value) {
...
// create new version, then call on all available versions
// POST call
this._newVersionService.createNewVersion(vnr);
// GET call
this._versionService.getAvailableVersions();
...
}
Run Code Online (Sandbox Code Playgroud)
在new-version.service.ts中:
export class NewVersionService {
response$: Subject<any>;
constructor(private _http: Http) {
this.response$ = new BehaviorSubject<any>(null);
}
public createNewVersion(versionNr) {
this._http.post('http://localhost:8080/services/' + versionNr, null, {
method: 'POST',
})
.subscribe(response => {
this.response$.next(response.status);
},
error => console.error(error));
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
我已经开始学习,Angular2但我想使用http.post()我的Web API 提交表单,但我不能.
angular ×10
typescript ×3
http ×2
javascript ×2
asynchronous ×1
chaining ×1
cors ×1
get ×1
header ×1
rest ×1
service ×1