angular 网络请求

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');



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值