SaveLolliPoP
@SaveLolliPoP
1 / 0 = ∞

В чем ошибка фильтра реализованного с помощью pipe?

Есть 2 компонента, new-task.component.ts:

import { Component, OnInit } from '@angular/core';
...
import { ShareService } from 'src/app/services/share.service';

@Component({
  selector: 'app-new-task',
  templateUrl: './new-task.component.html',
  styleUrls: ['./new-task.component.styl'],
  providers: [DatePipe]
})

export class NewTaskComponent implements OnInit {

  dataTasks: any[];
  Task = {
    actionValue: '',
    description: '',
    taskWhenDo: Date,
    lead_id: '',
    createdDate: ''
  };

  constructor(
    private myHTTP: myHTTPService,
    private datePipe: DatePipe,
    private share:ShareService
  ) {
    this.share.onChange.subscribe(cnt=>this.Task.lead_id = cnt);
  }

  ngOnInit() {
    this.getTasks();
  }
  async getTasks() {
    var dataTask = await this.myHTTP.postHTTP('/getTasks', {lead_id: this.Task.lead_id})
    .then( (res: Array<String>) => {
      return res;
    });
    var dataComment = await this.myHTTP.postHTTP('/getComments', {_id: this.Task.lead_id})
    .then( (res: Array<String>) => {
      return res;
    });
    return this.dataTasks = dataTask.concat(dataComment);
  }
}


Вывод this.dataTasks в new-task.component.html
<div class="col-12" *ngFor="let n of ( dataTasks | tasks )" style="padding: 0.5rem; border: 1px solid red;">
    <p>{{n.actionValue}}</p>
    <p>{{n.description}}</p>
    <p>{{n.taskWhenDo | date:'dd.MM.yyyy HH:mm'}}</p>
    <p>Дата создания: {{n.createdDate | date:'dd.MM.yyyy HH:mm'}}</p>
  </div>
</div>

Тут сортировка вывода filters.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
/*
 * Raise the value exponentially
 * Takes an exponent argument that defaults to 1.
 * Usage:
 *   value | exponentialStrength:exponent
 * Example:
 *   {{ 2 | exponentialStrength:10 }}
 *   formats to: 1024
*/
@Pipe({
    name: 'tasks'
})
export class FiltersPipeCustom implements PipeTransform {

  transform(tasks: any[]) {
      console.log(tasks);
    tasks.sort(function(a, b){
        return a.createdDate - b.createdDate;
    });
  }
}


lead-page.component.ts:

import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { myHTTPService } from 'src/app/services/HTTP/myhttp.service';
import { ShareService } from 'src/app/services/share.service';

@Component({
  selector: 'app-lead-page',
  templateUrl: './lead-page.component.html',
  styleUrls: ['./lead-page.component.styl']
})
export class LeadPageComponent implements OnInit {

  Lead = {
    _id: '',
    firmName: '',
    address: '',
    contactNumber: [],
    contactEmail: [],
    contactName: '',
    position: '',
    lprsName: '',
    parser2gis: ''
  };

  constructor(
    private route: ActivatedRoute,
    private myHttp: myHTTPService,
    private share: ShareService
  ) {
    this.share.onChange.subscribe(cnt => this.Lead._id = cnt);
  }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
    this.id = params['id'];
    this.getLeadInfo();
   });
  }
  async getLeadInfo() {
    var data = await this.myHttp.postHTTP('/getLeadInfo', {_id: this.id} );
    for (let x in data) {
		  for (let y in this.Lead) {
			  if (x == y) {
				  this.Lead[y] = data[x];
			  }
		  }
    }
    return this.share.shareVarible(this.Lead._id); //Тут вот инитиализируется передача переменной в другой компонент
  }
}


Далее сервис, который принимает переменную
import {EventEmitter} from '@angular/core';

export class ShareService {
  private leadId:string = '';
  
  onChange:EventEmitter<string> = new EventEmitter();

  public shareVarible (some){
      this.leadId = some;
    this.onChange.emit(this.leadId);
  }

}


В итоге такая вот ошибка
5c6b01ae4f5f0997660513.png

Как заставить работать эту сложную для меня схему?
Почему он выводит filters.pipe.ts:17 undefined, 2 раза, причем второй раз со значением?
  • Вопрос задан
  • 73 просмотра
Решения вопроса 1
Вы объявили значение dataTasks: any[];, но ничего ему не присвоили, оно равно undefined. Можно сделать так dataTasks: any[] = new Array();. Т.е. чтобы до того момента, пока данные не будут получены - там был массив а не undefined.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы