Android - filtros para una app de ionic

 
Vista:
Imágen de perfil de luana

filtros para una app de ionic

Publicado por luana (1 intervención) el 03/08/2021 10:41:55
Hola muy buenas, soy nueva en el foro y novata en programación y tengo un problema a la hora de implementar un sistema que cuando aplico unos filtros de búsqueda para mostrar un listado de productos se crea en la pagina unas etiquetas con los filtros seleccionados, esto funciona perfectamente, es decir entras en una pagina seleccionas los filtros que quieres y al apretar el botón de aplicar te devuelve a la pagina home y sale la lista correcta con los filtros y unas etiquetas con los filtros que se han marcado, pero después se ha colocado en la pagina home un menu tipo scroll que al apretar esos botones la lista de productos también se actualiza segun el botón que apretes pasando por mas filtros , esto se hizo para no tener que entrar en la pagina de filtros para que el usuario tuviera filtros mas accesibles. todo esto funciona bien, pero quería que al apretar los filtros del menu scroll de la home me aplicara también las etiquetas y la verdad no lo consigo implementar.

la app esta hecha con ionic , no se si alguien pudiera guiarme lo agradeceria

mira este es el codigo por si alguien puede ayudarme
en el html de home estas son las etiquetas y al final el menu scroll
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
32
33
34
35
36
37
38
39
<div class="filter_div" *ngIf="filterdata.apply_flag && (filterdata.filter_category.length>0 || filterdata.filter_distance.apply_flag || filterdata.filter_dates!='0' || filterdata.filter_type!='all' ||   filterdata.filter_maxprice>0 )">
 
 
 
    <div class="filter_item"  *ngIf="filterdata.filter_category.length>0" >
      <span style="margin:auto">{{filterdata.filter_category[0].title }}</span>
      <ion-icon name="close-circle-outline" class="filterclose_btn" (click)="filterdata.filter_category=[];refresh_filter()"></ion-icon>
    </div>
    <div class="filter_item" *ngIf="filterdata.filter_dates!='0'" (click)="filterdata.filter_dates='0';refresh_filter()">
       <span style="margin:auto">{{ get_filterdatestr(filterdata.filter_dates)}}</span>
      <ion-icon name="close-circle-outline" class="filterclose_btn"></ion-icon>
    </div>
 
    <div class="filter_item" *ngIf="filterdata.filter_type!='all'" (click)="filterdata.filter_type='all';refresh_filter()">
      <span style="margin:auto">{{ get_filtertype(filterdata.filter_type)}}</span>
     <ion-icon name="close-circle-outline" class="filterclose_btn"></ion-icon>
   </div>
 
    <div class="filter_item" *ngIf="filterdata.filter_maxprice>0" >
      <span style="margin:auto">{{filterdata.filter_minprice +'€'+ '  ~  ' + filterdata.filter_maxprice +'€'}}</span>
      <ion-icon name="close-circle-outline" class="filterclose_btn" (click)="filterdata.filter_minprice=0;filterdata.filter_maxprice=0;refresh_filter();"></ion-icon>
    </div>
 
    <div class="filter_item" *ngIf="filterdata.filter_distance.apply_flag" >
      <span style="margin:auto">{{filterdata.filter_distance.distance +'Km'+ ' ' + filterdata.filter_distance.city}}</span>
      <!--<ion-icon name="close-circle-outline" class="filterclose_btn" (click)="filterdata.filter_distance.apply_flag=false;refresh_filter();"></ion-icon>-->
      <ion-icon name="close-circle-outline" class="filterclose_btn" (click)="open_map()" ></ion-icon>
    </div>
  </div>
 
 <div>
    <ion-slides  [options]="sliderOpts" >
      <ion-slide *ngFor="let cate_item of api.shortcut_category_list" >
        <div class="group_item"  (click)="click_category(cate_item)" [ngStyle]="{'background':cate_item.category_id==sel_shortcut_cateid? 'orange':'none' }">
          <ion-img class="group_logo" [src]="cate_item?.image?cate_item?.image:'assets/noimage.png'"  ></ion-img>
        </div>
      </ion-slide>
    </ion-slides>
  </div>

esto es la pagina ts pongo todo el código es largo

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
export class HomePage implements OnInit {
 
  dummy = Array(20);
  product_list = [];
  search = "";
  dummy_product_list = [];
 
  sliderOpts = {
    autoplay: false,
    slidesPerView: 4,
    spaceBetween: 10,
    // speed: 2000,
  };
 
  sel_shortcut_cateid;
 
  filterdata = {
    shortcut_category_list: [],
    filter_category: [],
    filter_minprice: 0,
    filter_maxprice: 0,
    filter_type: 'all',
    filter_distance: {
      lat: this.api.userdata.lat,
      lng: this.api.userdata.lng,
      distance: 100,
      address: '',
      apply_flag: false
    },
    filter_dates: '0',
    apply_flag: false
  };
 
 
//para el mapa de la distancia
  distance_data = {
    lat: this.api.userdata.lat,
    lng: this.api.userdata.lng,
    distance: 100,
    address: '',
    city:'',
    apply_flag: false
  };
//fin mapa
  current_index = 0;
  segment_size = 6;
 
 
 
  constructor(
    public api: ApiService, public router: Router, public util: UtilService, public modalController: ModalController,
    private deepLink: Deeplinks,
  ) {
 
    this.sel_shortcut_cateid=0;
 
  }
 
  ngOnInit(): void {
 
  }
 
  processDeepLinks() {
    const product_id = localStorage.getItem('product_details');
    if (typeof (product_id) !== 'undefined' && product_id !== null && product_id !== '') {
      localStorage.removeItem('product_details');
      for (let list of this.product_list) {
        if (list.product_id.toString() === product_id) {
          this.open_product(list);
        }
      }
    }
  }
 
  ionViewWillEnter() {
 
    this.get_all_product();
    // this.includeCategory(130310);
 
    // this.api.deepLinkState.subscribe((result) => {
    //   console.log(result);
    //   this.get_all_product();
    // })
  }
 
  onSearchChange() {
    this.show_filteresult();
  }
 
  click_category(cate_item){
    if (this.sel_shortcut_cateid!=cate_item.category_id){
      this.sel_shortcut_cateid=cate_item.category_id;
      console.log(cate_item);
    } else
      this.sel_shortcut_cateid=0;
 
 
    console.log(this.sel_shortcut_cateid);
 
    this.show_filteresult();
  }
 
 
  get_all_product() {
    this.current_index = 0;
    this.segment_size = 6;
    var data = {
      'user_id': this.api.userdata.user_id,
      'api_token': this.api.userdata.api_token
    };
    this.dummy = Array(20);
 
    this.api.get_all_product(data).subscribe((res) => {
      this.dummy = [];
      if (res.status == '1') {
        var tmp_result = [];
 
        for (let i = 0; i < res.data.length; i++) {
          let distance = this.distanceInKmBetweenEarthCoordinates(this.api.userdata.lat, this.api.userdata.lng, res.data[i].lat, res.data[i].lng);
          res.data[i].distance = distance.toFixed(0);
 
          let start = moment(res.data[i].create_date, "YYYY-MM-DD");
          let end = moment().startOf('day');
 
          res.data[i].published_dates = moment.duration(end.diff(start)).asDays();
          tmp_result.push(res.data[i]);
        }
 
        tmp_result = orderBy(tmp_result, 'distance', 'asc');
 
        this.dummy_product_list = tmp_result;
        this.product_list = tmp_result;
        console.log(this.dummy_product_list);
 
        this.processDeepLinks();
 
        this.refresh_filter();
      } else {
        this.dummy_product_list = [];
        this.product_list = [];
      }
    }, error => {
 
      this.dummy = [];
      this.util.errorToast("Error en el servidor.");
    });
  }
 
  loadData(event) {
    var self = this;
    // setTimeout(() => {
    //   console.log('load more');
    //   self.current_index=self.current_index+self.segment_size;
    //    console.log(self.current_index);
    //   // console.log(this.dummy_message_list);
 
    //   var segment_array=self.dummy_product_list.slice(self.current_index,self.current_index+self.segment_size);
    //   // console.log(segment_array);
 
    //   self.product_list=self.product_list.concat(segment_array);
    //   // console.log(self.message_list);
 
    //   event.target.complete();
 
    //   // App logic to determine if all data is loaded
    //   // and disable the infinite scroll
    //   if (this.product_list.length >= this.dummy_product_list.length) {
    //     event.target.disabled = true;
    //   }
    // }, 500);
  }
 
  get_filterdatestr(filter_dateval) {
 
    if (filter_dateval == '0')
      return 'Todos los anuncios';
    else if (filter_dateval == '30')
      return 'Hace 30 dias';
    else if (filter_dateval == '7')
      return 'Hace 7 dias';
    else if (filter_dateval == '1')
      return 'Hace 24 horas';
  }
 
  get_filtertype(type_val) {
    if (type_val == 'all')
      return 'Todos';
    else if (type_val == 'particular')
      return 'Particular';
    else if (type_val == 'professional')
      return 'Professional';
  }
 
  distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) {
    //  console.log(lat1, lon1, lat2, lon2);
    const earthRadiusKm = 6371;
 
    const dLat = this.degreesToRadians(lat2 - lat1);
    const dLon = this.degreesToRadians(lon2 - lon1);
 
    lat1 = this.degreesToRadians(lat1);
    lat2 = this.degreesToRadians(lat2);
 
    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return earthRadiusKm * c;
  }
 
  degreesToRadians(degrees) {
    return degrees * Math.PI / 180;
  }
 
  open_product(item) {
    const navData: NavigationExtras = {
      queryParams: {
        product_details: JSON.stringify(item)
      }
    };
    this.router.navigate(['app/home/product_details'], navData);
  }
 
  open_chat(chat_item) {
 
    var data = {
      'user_id': this.api.userdata.user_id,
      'api_token': this.api.userdata.api_token,
      'type': 'product',
      'product_id': chat_item.product_id,
      'auction_id': 0,
      'seller_user_id': chat_item.user_id,
      'bid_user_id': this.api.userdata.user_id
    };
 
    this.util.show();
 
    this.api.open_chatroom(data).subscribe((res) => {
      console.log(res);
      this.util.hide();
      if (res.status == '1') {
        const navData: NavigationExtras = {
          queryParams: {
            chat_item: JSON.stringify(res.data)
          }
        };
        this.router.navigate(['chat'], navData);
      } else {
        this.util.errorToast("Can't open chat.Try again!");
      }
    }, error => {
      this.util.hide();
      this.util.errorToast("Error en el servidor.");
    });
 
 
  }
  //para el mapa de la distancia
  async open_map() {
 
    const modal = await this.modalController.create({
      component: MapPage,
      cssClass: 'modal-css-height-100',
      backdropDismiss: false,
      componentProps: {
        distance_data: this.distance_data,
      }
 
    });
 
    modal.onDidDismiss().then((dataReturned) => {
 
      console.log(dataReturned.data);
      if (dataReturned.data)
        this.distance_data = dataReturned.data;
      else
        this.distance_data = {
          lat: this.api.userdata.lat,
          lng: this.api.userdata.lng,
          distance: 100,
          address: '',
          city:'',
          apply_flag: false
        };
    });
 
    await modal.present().then(() => {
 
 
    });
 
  }
 
  async open_filter() {
    const modal = await this.modalController.create({
      component: FilterPage,
      backdropDismiss: false,
      componentProps: {
        'filterdata': this.filterdata
      }
    });
 
    modal.onDidDismiss().then((dataReturned) => {
      if (dataReturned && dataReturned.data) {
        this.filterdata = dataReturned.data;
        console.log(this.filterdata);
        this.show_filteresult();
      } else {
        console.log("No Filter");
      }
    });
    await modal.present().then(() => {
    });
  }
 
  includeCategory(cate_id) {
 
 
    var parent_id = cate_id;
 
    do {
      for (var i = 0; i < this.api.category_list.length; i++) {
        if (this.api.category_list[i].category_id == parent_id) {
          if (parent_id==this.filterdata.filter_category[0].category_id)    return true;
 
          parent_id = this.api.category_list[i].parent_id;
          break;
        }
      }
    } while (parent_id != 0)
 
    return false;
 
 
    /*
    var parent_id = cate_id;
    var selected_parentid = -1;
    //  console.log("------start--------");
    do {
      for (var i = 0; i < this.api.category_list.length; i++) {
        if (this.api.category_list[i].category_id == parent_id) {
          // console.log(this.api.category_list[i]);
          parent_id = this.api.category_list[i].parent_id;
          if (parent_id == 0)
            selected_parentid = this.api.category_list[i].category_id;
          break;
        }
      }
      if (parent_id === cate_id) break;
    } while (parent_id != 0)
    //  console.log("include category=",selected_parentid);
    if (selected_parentid == -1) {
      return false;
    } else {
      for (let j = 0; j < this.filterdata.filter_category.length; j++) {
        if (selected_parentid == this.filterdata.filter_category[j].category_id) {
          return true;
        }
      }
      return false;
    }
*/
 
 
  }
 
 
  include_Short_Category(cate_id) {
 
    var parent_id = cate_id;
 
    do {
      for (var i = 0; i < this.api.category_list.length; i++) {
        if (this.api.category_list[i].category_id == parent_id) {
          if (parent_id==this.sel_shortcut_cateid)    return true;
          parent_id = this.api.category_list[i].parent_id;
          break;
        }
      }
    } while (parent_id != 0)
 
    return false;
 
  }
 
 
  show_filteresult() {
    var tmp_list = this.dummy_product_list;
    var self = this;
 
    if (this.filterdata.filter_category.length > 0) {
      tmp_list = tmp_list.filter((item: any) => {
        if (this.includeCategory(item.category_id))
          return true;
        else
          return false;
      });
    }
 
    if (this.filterdata.filter_maxprice > 0) {
      tmp_list = tmp_list.filter((item: any) => {
        return item.price >= this.filterdata.filter_minprice && this.filterdata.filter_maxprice >= item.price;
      });
    }
 
    if (this.filterdata.filter_type != 'all') {
      tmp_list = tmp_list.filter((item: any) => {
        return this.filterdata.filter_type == item.kind;
      });
    }
 
    if (this.filterdata.filter_dates != '0') {
      tmp_list = tmp_list.filter((item: any) => {
        return item.published_dates < parseInt(this.filterdata.filter_dates);
      });
    }
 
 
    if (this.filterdata.filter_distance.apply_flag == true) {
      tmp_list = tmp_list.filter((item: any) => {
        let distance = this.distanceInKmBetweenEarthCoordinates(this.filterdata.filter_distance.lat, this.filterdata.filter_distance.lng, item.lat, item.lng);
        item.distance_filterval = distance;
        return item.distance_filterval <= this.filterdata.filter_distance.distance;
      });
      tmp_list = orderBy(tmp_list, 'distance_filterval', 'asc');
    }
 
 
    if (this.search != '') {
      tmp_list = tmp_list.filter((item: any) => {
        return item.title.toLowerCase().includes(this.search.toLowerCase());
      });
    }
 
 
    if (this.sel_shortcut_cateid != 0) {
      tmp_list = tmp_list.filter((item: any) => {
        if (this.include_Short_Category(item.category_id))
          return true;
        else
          return false;
      });
    }
 
 
 
 
    this.product_list = tmp_list;
    console.log(this.product_list);
  }
 
  refresh_filter() {
    console.log(this.filterdata);
    this.show_filteresult();
  }
 
 
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder