【发布时间】:2018-01-31 10:03:00
【问题描述】:
我是 Angular CLI 的初学者,我使用 http.post 使用了登录 api:'http://localhost/appointjobs/index.php/admin_api/index' 但是,当设置 'content-type:application/json' 时,我没有在服务器端(codeigniter/php)获取帖子数据.下面的代码是我在登录服务中使用的,当我使用'application/x-www-form-urlencoded' 而不是'application/json'时也会获取帖子数据。
DataService.ts file:
import { BadInputError } from './../common/bad-input-error';
import { error } from 'selenium-webdriver';
import { AppError } from './../common/app-error';
import { Observable } from 'rxjs/Observable';
import { Http, ResponseOptionsArgs,RequestOptionsArgs,Headers,RequestOptions } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
import { NotFoundError } from '../common/not-found-error';
import { Response } from '@angular/http/src/static_response';
import { HttpHeaders } from '@angular/common/http';
@Injectable()
export class DataService {
constructor(private http:Http) {
}
getWhere(url,resource){
let headers= new Headers();
//headers.append('Access-Control-Allow-Origin:','*');
headers.append('Accept','text/plain');
headers.append('content-type','application/json');
//headers.append('content-type','application/x-www-form-urlencoded');
let option= new RequestOptions({headers:headers});
return this.http.post(url,JSON.stringify(resource),option)
.map(response=>response.json())
.catch(this.handleError);
}
}
AuthService.ts 文件:
import { DataService } from './data.service';
import { Injectable } from '@angular/core';
@Injectable()
export class AuthService{
private url = 'http://localhost/appointjobs/index.php/admin_api/index';
constructor(private dataService:DataService) {
}
signIn(params:HTMLInputElement){
this.dataService.getWhere(this.url,params)
.subscribe(response=>{
console.log(response);
});
}
}
【问题讨论】:
-
你在哪里做
this.getWhere(url, resource).subscribe()?没有订阅,调用永远不会真正触发 -
你不必指定 headers.append('content-type','application/json');
-
1.不要使用 Http。它已被弃用。使用 HttpClient,如文档所述:angular.io/guide/http。 2. 如果您的后端 API 需要 JSON,您需要发送 JSON。如果它需要 application/x-www-form-urlencoded,您需要设置正确的内容类型标头,并以 application/x-www-form-urlencoded 格式传递键/值对。将内容类型设置为 application/x-www-form-urlencoded 并发送 JSON 正文没有任何意义。
-
@JBNizet 取决于他使用的是 angular2/4 还是 angular 5,但是是的,HttpClient 是更好的选择
-
@mast3rd3mon 他正在使用 Angular 4。但即使他使用的是 Angular 2,第一步也应该升级。
标签: angular angular-cli angular2-services angular-http