Angularv4.初体验
1474 浏览 5 years, 10 months
23 视频条目模型 Video Item Model
版权声明: 转载请注明出处 http://www.codingsoho.com/前面我们跟video相关的变量都是用的any类型,这个不够准确,我们这节把它映射到video对象。
参考json数据内的内容,我们设定模型VideoItem如下
src/app/videos/video.ts
export class VideoItem {
slug: string;
name: string;
image?: string;
embed?: string;
featured?: Boolean;
}
?表示这个字段是可选的
Json格式
src/assets/json/videos.json
"name": "Item 2",
"slug": "item-2",
"embed": "1hyjLD7pk10",
"image": "assets/images/nature/5.jpg",
"featured": false
我们接下来分别修改各个模块里的video字段
Video-list / video-detail / search-detail 的修改比较类似,导入这个模型,替换any类型就可以了
src/app/video-list/video-list.component.ts
import { VideoItem } from '../videos/video';
//videoList: [any];
videoList: [VideoItem];
ngOnInit() {
// this.todayDate = new Date()
this.req = this._video.list().subscribe(data=>{
//this.videoList = data as [any];
this.videoList = data as [VideoItem];
src/app/video-detail/video-detail.component.ts
import { VideoItem } from '../videos/video';
export class VideoDetailComponent implements OnInit, OnDestroy {
//video: any;
video: VideoItem;
ngOnInit() {
this.routeSub = this.route.params.subscribe(params => {
this.slug = params['slug']
this.req = this._video.get(this.slug).subscribe(data=>{
//this.video = data
this.video = data as VideoItem
src/app/search-detail/search-detail.component.ts
import { VideoItem } from '../videos/video';
//videoList: [any];
videoList: [VideoItem];
export class SearchDetailComponent implements OnInit, OnDestroy {
this.routeSub = this.route.params.subscribe(params=>{
this.query = params['q']
this.req = this._video.search(this.query).subscribe(data=>{
//this.videoList = data as [any];
this.videoList = data as [VideoItem];
})
})
主页的修改稍微有一些变化,除了和前面一样把list的类型改为VideoItem之外,顺便引入了service功能
用到了filter
src/app/home/home.component.ts
import { VideoItem } from '../videos/video';
import { VideoService } from '../videos/videos.service';
@Component({
providers: [VideoService]
})
export class HomeComponent implements OnInit, OnDestroy {
//homeImageList = [
// {image: "assets/images/nature/4.jpg", name:"Image 4", slug:'video-1'},
// {image: "assets/images/nature/5.jpg", name:"Image 5", link:'video-1'},
// {image: "assets/images/nature/6.jpg", name:"Image 6", link:'video-1'}
//]
homeImageList:[VideoItem] = [] as [VideoItem]
constructor(private http:Http, private router:Router, private _video:VideoService) { }
ngOnInit() {
//this.req = this.http.get('assets/json/videos.json').subscribe(data=>{
this.req = this._video.list().subscribe(data=>{
//console.log(data.json())
data.json().filter(item=>{
data.filter(item=>{
if(item.featured){
//this.homeImageList.push(item)
let dataItem = item
this.homeImageList.push(dataItem)
}
})
视频上额外做了一步赋值,不知道为什么
修改Item2的featured为true,这样它也能显示在主页上。
src/assets/json/videos.json
"name": "Item 2",
"slug": "item-2",
"embed": "1hyjLD7pk10",
"image": "assets/images/nature/5.jpg",
#"featured": false
"featured": true