import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core'; import { Observable } from "rxjs"; import { Store } from '@ngrx/store'; import { Subscription } from 'rxjs/Subscription'; import { HttpService } from '../shared/services/http/http.service'; import { PetTag } from './model/pet-tag.model'; import { PettagActions } from './action/pet-tag.actions'; @Component({ selector: 'demo-pet', styleUrls: ['./demopet.scss'], templateUrl: './demopet.html' }) export class DemoPetComponent { private sub: Subscription; public dataArr: any; public dataItem: any; public language: string = 'en'; public param = {value: 'world'}; constructor( private store: Store<PetTag>, private action: PettagActions ) { this.dataArr = store.select('pet'); } ngOnInit() { this.store.dispatch(this.action.loadData()); } ngOnDestroy() { this.sub.unsubscribe(); } info() { console.log('info'); this.dataItem = this.store.select('info'); this.store.dispatch(this.action.loadInfo()); } }
demopet.html
<h1>Demo</h1> <pre> <ul> <li *ngFor="let d of dataArr | async"> DEMO : {{ d.msg }} <button (click)="info()">info</button> </li> </ul> {{ dataItem | async | json }} <h1 *ngFor="let d of dataItem | async"> {{ d.msg }} </h1> </pre>
6.运行效果
初始化时候获取数据列表
点击info按钮 获取详细详细
7.以上代码是从项目中取出的部分代码,其中涉及到HttpService需要自己封装,data.json demo.json两个测试用的json文件,名字随便取的当时。
http.service.ts
import { Inject, Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'; import { Observable } from "rxjs"; import 'rxjs/add/operator/map'; import 'rxjs/operator/delay'; import 'rxjs/operator/mergeMap'; import 'rxjs/operator/switchMap'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import { handleError } from './handleError'; import { rootPath } from './http.config'; @Injectable() export class HttpService { private _root: string=""; constructor(private http: Http) { this._root=rootPath; } public get(url: string, data: Map<string, any>, root: string = this._root): Observable<any> { if (root == null) root = this._root; let params = new URLSearchParams(); if (!!data) { data.forEach(function (v, k) { params.set(k, v); }); } return this.http.get(root + url, { search: params }) .map((resp: Response) => resp.json()) .catch(handleError); } }