ОШИБКА TS2551: свойство 'posts' не существует - PullRequest
0 голосов
/ 02 марта 2019

enter image description here Я пытаюсь запустить его, но он не может выполнить результаты поиска.Точнее, не отображается поиск по названию.

терминал отображает эту ошибку:

ОШИБКА в src / app / app.component.ts (19,11): ошибка TS2551: Свойство «posts» не существует для типа «AppComponent».Вы имели в виду «post»?

Пожалуйста, помогите

Data.service.ts

import { Injectable } from '@angular/core';
import { Post } from './post';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders} from '@angular/common/http';


@Injectable({
  providedIn: 'root'
})

export class DataService {

 searchOption=[]

 public postsData: Post[]

 postUrl: string = "https://jsonplaceholder.typicode.com/posts";

  constructor(private http: HttpClient) {}

  getPosts(): Observable<Post[]> {
   return this.http.get<Post[]>(this.postUrl)
 }

 filteredListOptions() {
     let posts = this.postsData;
         let filteredPostsList = [];
         for (let post of posts) {
             for (let options of this.searchOption) {
                 if (options.title === post.title) {
                   filteredPostsList.push(post);
                 }
             }
         }
         console.log(filteredPostsList);
         return filteredPostsList;
   }

}

App.component.ts

import { Component } from '@angular/core';
import { Post } from './post';
import { DataService } from './data.service';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'API';

  post: Post[];

   constructor(private dataService: DataService) {}

    getPosts() {
     this.posts = this.dataService.getPosts()
   }


   ngOnInit() {
     this.dataService.getPosts().subscribe(posts => {
       this.post = posts
       this.dataService.postsData = posts
     });
   }

   onSelectedOption(e) {
     this.getFilteredExpenseList();
   }

   getFilteredExpenseList() {
     if (this.dataService.searchOption.length > 0)
       this.post = this.dataService.filteredListOptions();
     else {
       this.post = this.dataService.postsData;
     }

     console.log(this.post)
   }

}

App.component.html

<div style="text-align:center">
  <h1>
    {{ title }}!
  </h1>
  <div>
    <button (click)="getPosts()"> Get Posts!</button>
  </div>

    <div>

    <app-search-bar (onSelectedOption)="onSelectedOption($event)"></app-search-bar>

    </div>
    <h2 style="text-align:center">Data</h2>
    <div *ngFor="let post of posts | async" class="group">
      <p><b>Title :</b> {{post.title}}</p>
      <p><b>Body: </b>{{post.body}}</p>
    </div>


</div>

Search-bar.companent.ts

import { Component, OnInit, ViewChild, ElementRef,EventEmitter,Output } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { DataService } from '../../data.service';
import { Post } from '../../post';

@Component({
  selector: 'app-search-bar',
  templateUrl: './search-bar.component.html',
  styleUrls: ['./search-bar.component.css']
})
export class SearchBarComponent implements OnInit {

  myControl = new FormControl();
  filteredOptions: Observable<string[]>;
  allPosts: Post[];
  autoCompleteList: any[]

  @ViewChild('autocompleteInput') autocompleteInput: ElementRef;
  @Output() onSelectedOption = new EventEmitter();

  constructor(
    private dataService: DataService
  ) { }

  ngOnInit() {
    this.dataService.getPosts().subscribe(posts => {
      this.allPosts = posts

    });

    this.myControl.valueChanges.subscribe(userInput => {
      this.autoCompleteExpenseList(userInput);
    })
  }

  private autoCompleteExpenseList(input) {
    let categoryList = this.filterCategoryList(input)
    this.autoCompleteList = categoryList;
  }

  filterCategoryList(val) {
    var categoryList = []
    if (typeof val != "string") {
      return [];
    }
    if (val === '' || val === null) {
      return [];
    }
    return val ? this.allPosts.filter(s => s.title.toLowerCase().indexOf(val.toLowerCase()) != -1)
      : this.allPosts;
  }

  displayFn(post: Post) {
    let k = post ? post.title : post;
    return k;
  }

  filterPostList(event) {
    var posts= event.source.value;
        if(!posts) {
          this.dataService.searchOption=[]
        }
        else {
          console.log("not")

            this.dataService.searchOption.push(posts);
            this.onSelectedOption.emit(this.dataService.searchOption)
        }

        this.focusOnPlaceInput();



  }


  removeOption(option) {

    let index = this.dataService.searchOption.indexOf(option);
    if (index >= 0)
        this.dataService.searchOption.splice(index, 1);
        this.focusOnPlaceInput();

        this.onSelectedOption.emit(this.dataService.searchOption)
}

focusOnPlaceInput() {
  this.autocompleteInput.nativeElement.focus();
  this.autocompleteInput.nativeElement.value = '';
}
}

Search-bar.component.html

import { Component, OnInit, ViewChild, ElementRef,EventEmitter,Output } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { DataService } from '../../data.service';
import { Post } from '../../post';

@Component({
  selector: 'app-search-bar',
  templateUrl: './search-bar.component.html',
  styleUrls: ['./search-bar.component.css']
})
export class SearchBarComponent implements OnInit {

  myControl = new FormControl();
  filteredOptions: Observable<string[]>;
  allPosts: Post[];
  autoCompleteList: any[]

  @ViewChild('autocompleteInput') autocompleteInput: ElementRef;
  @Output() onSelectedOption = new EventEmitter();

  constructor(
    private dataService: DataService
  ) { }

  ngOnInit() {
    this.dataService.getPosts().subscribe(posts => {
      this.allPosts = posts

    });

    this.myControl.valueChanges.subscribe(userInput => {
      this.autoCompleteExpenseList(userInput);
    })
  }

  private autoCompleteExpenseList(input) {
    let categoryList = this.filterCategoryList(input)
    this.autoCompleteList = categoryList;
  }

  filterCategoryList(val) {
    var categoryList = []
    if (typeof val != "string") {
      return [];
    }
    if (val === '' || val === null) {
      return [];
    }
    return val ? this.allPosts.filter(s => s.title.toLowerCase().indexOf(val.toLowerCase()) != -1)
      : this.allPosts;
  }

  displayFn(post: Post) {
    let k = post ? post.title : post;
    return k;
  }

  filterPostList(event) {
    var posts= event.source.value;
        if(!posts) {
          this.dataService.searchOption=[]
        }
        else {
          console.log("not")

            this.dataService.searchOption.push(posts);
            this.onSelectedOption.emit(this.dataService.searchOption)
        }

        this.focusOnPlaceInput();



  }


  removeOption(option) {

    let index = this.dataService.searchOption.indexOf(option);
    if (index >= 0)
        this.dataService.searchOption.splice(index, 1);
        this.focusOnPlaceInput();

        this.onSelectedOption.emit(this.dataService.searchOption)
}

focusOnPlaceInput() {
  this.autocompleteInput.nativeElement.focus();
  this.autocompleteInput.nativeElement.value = '';
}


}

1 Ответ

0 голосов
/ 02 марта 2019

Вам просто нужно добавить posts: any; или любой другой тип, который вы хотите, к app.component.ts в post: Post[];

. Чтобы выполнить поиск, вам просто нужно изменить this.post на this.posts вgetFilteredExpenseList()

getFilteredExpenseList() {
     if (this.dataService.searchOption.length > 0)
       this.posts = this.dataService.filteredListOptions();
     else {
       this.posts = this.dataService.postsData;
     }
     console.log(this.posts)
   }

Вы просто должны добавить posts: any; или любой другой тип, который вы хотите, к app.component.ts в post: Post[];

. Чтобы выполнить поиск, вам сначала нужно изменитьthis.post до this.posts в getFilteredExpenseList()

getFilteredExpenseList() {
     if (this.dataService.searchOption.length > 0)
       this.posts = this.dataService.filteredListOptions();
     else {
       this.posts = this.dataService.postsData;
     }
     console.log(this.posts)
   }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...