我们有时希望像后端语言一样,让angular获取的网络json能够转化为一个数据entity的实体对象集合。
比如我们有一个json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
{ "items": [{ "id": 11, "title": "Dr Nice" }, { "id": 12, "title": "Narco" }, { "id": 13, "title": "Bombasto" }, { "id": 14, "title": "Celeritas" } ] } |
对应每一个数据,我们为angular创建了一个实体
\src\app\model\news.model.ts
1 2 3 4 5 6 7 8 9 |
export class news{ id: string; title: string; constructor(obj?: any){ this.id = obj && obj.id || null; this.title = obj && obj.title || null; } } |
准备工作已经完毕,我们首先要网络获取这个json的数据。这个操作我们把它写在服务里
先创建一个服务
1 |
ng generate service /service/news |
然后,在服务里
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import { Injectable } from '@angular/core'; import { Observable, throwError } from 'rxjs'; import { news } from '../model/news.model'; import { HttpClient } from "@angular/common/http"; import { map,catchError, retry } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class NewsService { private apiurl :string; constructor(private http:HttpClient) { # 普通方式获取json内容 this.apiurl = "http://localhost/news.json"; this.http.get( this.apiurl).subscribe(result => { console.log(result); }); } //下面方法可以将json转化为news对象并放入数组中 getall():Observable<news[]>{ return this.http.get(this.apiurl).pipe( map(reponse => { return <any>reponse['items'].map(item =>{ return new news({ id: item.id, title: item.title }); }); }), ); } } |
不要忘记在app.module.ts中引用HttpClientModule
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
..... import {HttpClientModule} from '@angular/common/http'; @NgModule({ declarations: [ AppComponent, ...... ], imports: [ BrowserModule, ...... HttpClientModule, ..... export class AppModule { } |
好了,万事具备只欠东风,我们来使用之前服务里写好的getall方法吧
\src\app\newslist\newslist.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import { Component, OnInit, Output } from '@angular/core'; import { NewsService } from '../service/news.service'; @Component({ selector: 'app-newslist', templateUrl: './newslist.component.html', styleUrls: ['./newslist.component.less'] }) export class NewslistComponent implements OnInit { public newslist:any; constructor(private newsservice: NewsService) { } ngOnInit(): void { this.newsservice.getall().subscribe(result => { console.log(result); this.newslist=result; }); } } |
页面我是用的ngx-weui
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<div class="weui-panel weui-panel_access"> <div class="weui-panel__hd">最新资讯</div> <div class="weui-panel__bd"> <a href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg" *ngFor="let item of newslist"> <div class="weui-media-box__hd"> <img class="weui-media-box__thumb" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAMAAAAOusbgAAAAeFBMVEUAwAD///+U5ZTc9twOww7G8MYwzDCH4YcfyR9x23Hw+/DY9dhm2WZG0kbT9NP0/PTL8sux7LFe115T1VM+zz7i+OIXxhes6qxr2mvA8MCe6J6M4oz6/frr+us5zjn2/fa67rqB4IF13XWn6ad83nxa1loqyirn+eccHxx4AAAC/klEQVRo3u2W2ZKiQBBF8wpCNSCyLwri7v//4bRIFVXoTBBB+DAReV5sG6lTXDITiGEYhmEYhmEYhmEYhmEY5v9i5fsZGRx9PyGDne8f6K9cfd+mKXe1yNG/0CcqYE86AkBMBh66f20deBc7wA/1WFiTwvSEpBMA2JJOBsSLxe/4QEEaJRrASP8EVF8Q74GbmevKg0saa0B8QbwBdjRyADYxIhqxAZ++IKYtciPXLQVG+imw+oo4Bu56rjEJ4GYsvPmKOAB+xlz7L5aevqUXuePWVhvWJ4eWiwUQ67mK51qPj4dFDMlRLBZTqF3SDvmr4BwtkECu5gHWPkmDfQh02WLxXuvbvC8ku8F57GsI5e0CmUwLz1kq3kD17R1In5816rGvQ5VMk5FEtIiWislTffuDpl/k/PzscdQsv8r9qWq4LRWX6tQYtTxvI3XyrwdyQxChXioOngH3dLgOFjk0all56XRi/wDFQrGQU3Os5t0wJu1GNtNKHdPqYaGYQuRDfbfDf26AGLYSyGS3ZAK4S8XuoAlxGSdYMKwqZKM9XJMtyqXi7HX/CiAZS6d8bSVUz5J36mEMFDTlAFQzxOT1dzLRljjB6+++ejFqka+mXIe6F59mw22OuOw1F4T6lg/9VjL1rLDoI9Xzl1MSYDNHnPQnt3D1EE7PrXjye/3pVpr1Z45hMUdcACc5NVQI0bOdS1WA0wuz73e7/5TNqBPhQXPEFGJNV2zNqWI7QKBd2Gn6AiBko02zuAOXeWIXjV0jNqdKegaE/kJQ6Bfs4aju04lMLkA2T5wBSYPKDGF3RKhFYEa6A1L1LG2yacmsaZ6YPOSAMKNsO+N5dNTfkc5Aqe26uxHpx7ZirvgCwJpWq/lmX1hA7LyabQ34tt5RiJKXSwQ+0KU0V5xg+hZrd4Bn1n4EID+WkQdgLfRNtvil9SPfwy+WQ7PFBWQz6dGWZBLkeJFXZGCfLUjCgGgqXo5TuSu3cugdcTv/HjqnBTEMwzAMwzAMwzAMwzAMw/zf/AFbXiOA6frlMAAAAABJRU5ErkJggg==" alt="" /> </div> <div class="weui-media-box__bd"> <h4 class="weui-media-box__title">{{item.title}}</h4> <p class="weui-media-box__desc"> 由各种物质组成的巨型球状天体,叫做星球。星球有一定的形状,有自己的运行轨道。 </p> </div> </a> </div> </div> |
我只替换了title,展示效果如下:
全局newslist变量
为了日后方便,我们将newslist变量放到服务中去,也就是让他在内存中保存下来,以方便其他页面调用newslist。
\src\app\service\news.service.ts
1 2 3 4 5 |
export class NewsService { //接收外部传来的数据,作为内存下的全局变量 public newslist:Array<news>; private apiurl :string; |
改写\src\app\newslist\newslist.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import { Component, OnInit, Output } from '@angular/core'; import { NewsService } from '../service/news.service'; @Component({ selector: 'app-newslist', templateUrl: './newslist.component.html', styleUrls: ['./newslist.component.less'] }) export class NewslistComponent implements OnInit { public newslist:any; constructor(public newsservice: NewsService) { } ngOnInit(): void { this.newsservice.getall().subscribe(result => { this.newsservice.newslist=result; }); } } |
这里主要改了两个地方,
private变为了public为了模板可以访问
this.newslist 变为了给newsservice里的newslist赋值
如果你要追加新的数据可以这样
1 2 3 4 5 |
this.newsservice.getall().subscribe(result => { result.forEach(item =>{ this.newsservice.newslist.push(item); }); }); |
好了,该改写模板了
1 |
*ngFor="let item of newsservice.newslist"> |
可以访问你的页面看看效果了。
其他页面获取这个newslist对象可以这样
1 2 3 |
ngOnInit(): void { console.log(this.newsservice.newslist); } |
完事!