Angularv4.初体验
1290 浏览 5 years, 10 months
15 Http请求 Http Requests
版权声明: 转载请注明出处 http://www.codingsoho.com/15 -- Http Requests 在前面VideoList的内容列表我们是预定义在代码里的,这节我们将通过的Http的方式从外部获取。
创建文件assets/json/videos.json 并将下面这个定义的数组
videoList = [
{
name: 'Item 1',
slug: 'item-1',
// embed: `XMzU5MjI4NTI3Mg`,
embed: `95851db6%2Dd22f%2D4e32%2D8d7c%2Dc06a907f9457`,
},
{
name: 'Item 2',
slug: 'item-2',
// embed: `XMzU5MjI4NTI3Mg`,
embed: `10d528b2%2Ddc88%2D4ad5%2D8bb5%2D7aceff22c5ef`,
},
{
name: 'Item 3',
slug: 'item-3',
embed: null,
}
]
在json文件里定义如下
[
{
"name": "Item 1",
"slug": "item-1",
"embed": "95851db6%2Dd22f%2D4e32%2D8d7c%2Dc06a907f9457"
},
{
"name": "Item 2",
"slug": "item-2",
"embed": "10d528b2%2Ddc88%2D4ad5%2D8bb5%2D7aceff22c5ef"
},
{
"name": "Item 3",
"slug": "item-3",
"embed": null,
}
]
注意:每个字典最后一个元素转换不能有逗号,否则报错
接下来我们需要在页面加载时通过Http Request获取这些数据。
在video-list.component.ts添加支持
import { Http } from '@angular/http';
private req:any
constructor(private http:Http) { }
ngOnInit() {
this.req = this.http.get("assets/json/videos.json").subscribe(data=>{
console.log(data.json())
})
}
ngOnDestory(){
this.req.unsubscribe()
}
确保app.modules.ts里HttpModule已导入
import { HttpModule } from '@angular/http';
@NgModule({
imports: [
//ngx-bootstraps
BsDropdownModule.forRoot(),
CarouselModule.forRoot(),
BrowserModule,
AppRoutingModule,
HttpModule,
],
上面的代码中我们已经能够从json文件中获取配置内容了,接下来将这些内容应用到模板中
videoList : [any];
ngOnInit() {
this.req = this.http.get("assets/json/videos.json").subscribe(data=>{
this.videoList = data.json() as [any];
})
}
接下来,在video-detail中进行更新
在video-detail.component.ts添加json数据的处理
同样,导入http模块。在OnInit函数是将对应的json数据赋值给video变量
import { Http } from '@angular/http';
private req:any
video: any;
constructor(private route: ActivatedRoute, private http:Http) { }
ngOnInit() {
this.routeSub = this.route.params.subscribe(params => {
this.slug = params['slug']
this.req = this.http.get("assets/json/videos.json").subscribe(data=>{
data.json().filter(item=>{
if(item.slug == this.slug){
this.video = item
}
})
})
})
}
ngOnDestroy() {
this.routeSub.unsubscribe()
this.req.unsubscribe()
}
在html添加模板内容
<h1>{{video.name}}</h1>
<p>
{{video.slug}}
</p>
如果仅仅是上面内容,会报错,因为刚开始加载时,数据内容还没赋值,这个时候模板的渲染会出错。
可以有几个方法来解决
- 添加默认变量
video = {
name: 'Item 1',
slug: 'item-1',
embed: `95851db6%2Dd22f%2D4e32%2D8d7c%2Dc06a907f9457`,
}
- 添加判断*ngIF
<div *ngIf="video">
<h1>{{video.name}}</h1>
<p>
{{video.slug}}
</p>
</div>
- 添加判断?
<div *ngIf="!video">Loading</div>
<h1>{{video?.name}}</h1>
<p>
{{video?.slug}}
</p>