demo13.component.ts
import { Component, OnInit } from '@angular/core';
import {MyHttpService} from './myhttp.service';
@Component({
selector: 'demo13',
template: `
<h2>http</h2>
<button (click)="handleClick()">按钮</button>
`
})
export class Demo13Component implements OnInit {
constructor(private myHS:MyHttpService) { }
ngOnInit() { }
handleClick(){
this.myHS.sendRequest('http://jsonplaceholder.typicode.com/posts').subscribe((result)=>{
console.log(result);
});
}
}
myhttp.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class MyHttpService {
constructor(private http: Http) { }
sendRequest(myUrl:string){
//a-http-get
return this.http.get(myUrl,{withCredentials:true}) //withCredentials 携带凭证,如果服务器是php,需要加两个请求头
.map((response: Response) => response.json());
}
}
app.module.ts:
import {
HttpModule}
from
'@angular/http';
import {
MyHttpService}
from
'./demo13/myhttp.service';
@
NgModule({
providers:[
HeartService,
MyHttpService],
imports: [
BrowserModule,
FormsModule,
HttpModule ],
header('Access-Control-Allow-Origin:http://localhost:3000');
header('Access-Control-Allow-Credentials: true');