Angularv4.初体验


855 浏览 3 years, 10 months

16 特色 Http & Featured

版权声明: 转载请注明出处 http://www.codingsoho.com/

本文将在主页直接访问视频和图片

将homeImageList内容拷贝到json文件

[
  {
    "name": "Item 1",
    "slug": "item-1",
    "embed": "95851db6%2Dd22f%2D4e32%2D8d7c%2Dc06a907f9457",
    "image":"assets/images/nature/4.jpg"
  },
  {
    "name": "Item 2",
    "slug": "item-2",
    "embed": "10d528b2%2Ddc88%2D4ad5%2D8bb5%2D7aceff22c5ef",
    "image":"assets/images/nature/5.jpg"
  },
  {
    "name": "Item 3",
    "slug": "item-3",
    "embed": null,
    "image":"assets/images/nature/6.jpg"
  }
]

同样添加Http支持,并在Init和Destroy函数里注册和销毁

修改homeImageList名字,使其与json文件一致

import { Http} from '@angular/http'

  private req:any;

  homeImageList = [
    { image: "assets/images/nature/4.jpg", name:"Image 4", slug:"video-1"},
    { image: "assets/images/nature/5.jpg", name:"Image 5", slug:"video-1"},
    { image: "assets/images/nature/6.jpg", name:"Image 6", slug:"video-1"},
  ]

  constructor(private http:Http, private router:Router) { }

  ngOnInit() {
    this.req = this.http.get("assets/json/videos.json").subscribe(data=>{
      console.log(data.json())
      this.homeImageList = data.json();
    })    
  }

  ngOnDestroy(){
    this.req.unsubscribe()
  }

同时更新home.component.html内容, 前面homeImageList讲title改成了name,href改成了slug,这儿也要做相应修改。

        <div class="carousel-caption d-none d-md-block">
          <h3>{{ imageObj.name }}</h3>
          <a class="btn btn-default" href="/videos/{{ imageObj.slug }}"> View</a>
        </div>

前面的函数中,homeImageList的内容是从json文件一次性读取覆盖的,有的时候我们希望选择性的显示。

例如,主页我们只想显示一些精选内容,我们可以设置变量featured,然后根据是否为true来显示

首先,我们可以注销在home.component.ts里定义

  homeImageList = [
    // { image: "assets/images/nature/4.jpg", name:"Image 4", slug:"videos/video-1"},
    // { image: "assets/images/nature/5.jpg", name:"Image 5", slug:"videos/video-1"},
    // { image: "assets/images/nature/6.jpg", name:"Image 6", slug:"videos/video-1"},
  ]

在OnInit函数里根据featured变量是否设置将对应的条目push进homeImageList

  ngOnInit() {
    this.req = this.http.get("assets/json/videos.json").subscribe(data=>{
      console.log(data.json())
      data.json().filter(item=>{
        if(item.featured){
          this.homeImageList.push(item)
        }
      })
      // this.homeImageList = data.json();
    })    
  }

如果json文件设置如下,那么在主页最终只有Item1会被显示。

[
  {
    "name": "Item 1",
    "slug": "item-1",
    "embed": "95851db6%2Dd22f%2D4e32%2D8d7c%2Dc06a907f9457",
    "image":"assets/images/nature/4.jpg",
    "featured":true
  },
  {
    "name": "Item 2",
    "slug": "item-2",
    "embed": "10d528b2%2Ddc88%2D4ad5%2D8bb5%2D7aceff22c5ef",
    "image":"assets/images/nature/5.jpg",
    "featured":false
  },
  {
    "name": "Item 3",
    "slug": "item-3",
    "embed": null,
    "image":"assets/images/nature/6.jpg"
  }
]