Angular2官網經過http請求模擬API 來請求hero 數據,感受有點繁瑣,很讓人理解不了,咱們不採用它的辦法,直接展現怎麼使用http請求來獲取咱們的數據 ,直截了當。html
建立一個webapi(這裏我使用MVC4 WebApi ,你能夠選擇其餘途徑提供json數據,根據本身須要),返回新聞列表 web
public class NewsController : ApiController { public IEnumerable<News> Get() { return AllNews; } public News Get(int id) { return AllNews.Where(m => m.id == id).First(); } public List<News> AllNews { get { return new List<News>() { new News(){ id=1,title="title1", click=0, create_date="2017-10-20"}, new News(){ id=2,title="title2", click=0, create_date="2017-10-20"}, new News(){ id=3,title="title3", click=0, create_date="2017-10-20"}, new News(){ id=4,title="title4", click=0, create_date="2017-10-20"}, new News(){ id=5,title="title5", click=0, create_date="2017-10-20"}, new News(){ id=6,title="title6", click=0, create_date="2017-10-20"}, }; } } }
因爲咱們的ajax請求跨域,須要設置容許跨域請求,能夠在web.config中增長如下配置ajax
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> </customHeaders> </httpProtocol> </system.webServer>
1. 在news.service.ts 中 增長 http模塊導入 npm
import { Http,Response } from '@angular/http'; import 'rxjs/add/operator/toPromise';
增長構造函數,修改getNews 方法json
constructor(private http:Http){} getNews() { return this.http.get("http://localhost:63387/api/news/").toPromise() .then(response=>response.json()) .catch((err)=>{ console.log(err); }); }
最終代碼bootstrap
import { Injectable } from "@angular/core"; import { News } from './news'; import { NewList } from './mock-news';
import { Http,Response } from '@angular/http'; import 'rxjs/add/operator/toPromise'; @Injectable() export class NewsService { constructor(private http:Http){} getNews() { return this.http.get("http://localhost:63387/api/news/").toPromise() .then(response=>response.json()) .catch((err)=>{ console.log(err); }); } }
2. 修改app.module.ts ,增長HttpModule 支持api
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { NewsListComponent } from './news/newslist.component'; import { NewsDetailComponent } from './news/news-detail.component'; import { AppComponent } from './app.component'; import {NewsService} from './news/news.service'; import{ HttpModule} from '@angular/http'; @NgModule({ declarations: [ AppComponent, NewsListComponent, NewsDetailComponent ], imports: [ BrowserModule, FormsModule, HttpModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
導入 import{ HttpModule} from '@angular/http';跨域
在 imports 中增長HttpModuleapp
npm start 能夠看到能正常顯示咱們的數據了ide
1. 在須要的Service中,增長導入 Http