динамическое изменение элемента фона в ионном режиме (данные с сервера json) - PullRequest
0 голосов
/ 17 октября 2018

Я хочу разработать приложение, которое получает данные с json-сервера для загрузки списков, и когда я щелкаю по элементу, меняется цвет ее фона и атрибут ischlicked на true.это мой код home.html:

<ion-header>
  <ion-navbar>
    <ion-title>home</ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>

  <ion-list class="notifications-list">
    <ion-item *ngFor="let notification of notifications" (click)="onItemClick(notification)" [ngStyle]="{ background: notification.isClicked ? '#F6F6F6': '#E4E9F1'}">
      <img width="20" src="{{BaseURL + notification.image}}" item-start />
      <b>{{notification.name1}}</b><br>{{notification.name2}}<br> {{notification.name3}}
      <label item-end>{{notification.time}}</label>
    </ion-item>

  </ion-list>
</ion-content>

это мой код home.ts:

import { Component, OnInit, Inject } from '@angular/core';
import { ViewController, IonicPage, NavController } from 'ionic-angular';
import { Notification } from '../../shared/notification';
import { NotificationProvider } from '../../providers/notification/notification';


@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
})
export class HomePage implements OnInit {
  notifications: Notification[];
  notificationErrMess: string;


  constructor(public viewCtrl: ViewController,
    private notificationservice: NotificationProvider,
    @Inject('BaseURL') private BaseURL) {

  }
  ionViewDidLoad() {
    console.log('ionViewDidLoad NotificationPage');

  }
  ngOnInit() {
    this.notificationservice.getNotifications()
      .subscribe(notifications => this.notifications = notifications,
        errmess => this.notificationErrMess = <any>errmess);
  }

  onItemClick(notification) {

    if (notification.isClicked == false) {
      notification.isClicked = true;
    }
    //else {
    //   div.isClicked = true;
    // }

  }


}

это код моего поставщика уведомлений.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Notification } from '../../shared/notification';
import { Observable } from 'rxjs/Observable';
import { Http, Response } from '@angular/http';
import { baseURL } from '../../shared/baseurl';
import { ProcessHttpmsgProvider } from '../process-httpmsg/process-httpmsg';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/catch';
@Injectable()
export class NotificationProvider {

  constructor(public http: Http,
    private processHTTPMsgService: ProcessHttpmsgProvider) {

    console.log('Hello NotificationProvider Provider');
  }

  getNotifications(): Observable<Notification[]> {
    return this.http.get(baseURL + 'notifications')
      .map(res => { return this.processHTTPMsgService.extractData(res); })
      .catch(error => { return this.processHTTPMsgService.handleError(error); });
  }

  getNotification(id: number): Observable<Notification> {
    return this.http.get(baseURL + 'notifications/' + id)
      .map(res => { return this.processHTTPMsgService.extractData(res); })
      .catch(error => { return this.processHTTPMsgService.handleError(error); });
  }

  getClickedNotification(): Observable<Notification> {
    return this.http.get(baseURL + 'notifications?isClicked=true')
      .map(res => { return this.processHTTPMsgService.extractData(res)[0]; })
      .catch(error => { return this.processHTTPMsgService.handleError(error); });
  }

  getUnClickedNotification(): Observable<Notification> {
    return this.http.get(baseURL + 'notifications?isClicked=false')
      .map(res => { return this.processHTTPMsgService.extractData(res)[0]; })
      .catch(error => { return this.processHTTPMsgService.handleError(error); });
  }

}

это мой провайдер process-httpmsg.ts:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Response } from '@angular/http';
import 'rxjs/add/observable/throw';

@Injectable()
export class ProcessHttpmsgProvider {

  constructor(public http: Http) {
    console.log('Hello ProcessHttpmsgProvider Provider');
  }

  public extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  public handleError(error: Response | any) {
    // In a real world app, you might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}

это мой интерфейс уведомлений:

export interface Notification {
    id: number;
    image: string;
    name1 : string;
    name2 : string;
    name3 : string;
    time : string;
    isClicked: boolean;
    page: string;

}

это мой файл baseurl:

export const baseURL = 'http://localhost:3000/';

это мой файл db.json:

{
  "notifications": [
    {
      "id": 0,
      "image": "images/buffet.png",
      "name1": "name1",
      "name2": "name2",
      "name3": "name3",
      "time":  "time",
      "isClicked": "true",
      "page": "oasis"
    },
    {
      "id": 1,
      "image": "images/buffet.png",
      "name1": "name1",
      "name2": "name2",
      "name3": "name3",
      "time":  "time",
      "isClicked": "false",
      "page": "oasis"
    }
  ]
}
...