错误错误TS2551:属性“帖子”不存在

时间:2019-03-02 00:05:44

标签: angular typescript angular-components

enter image description here我正在尝试运行它,但是它无法执行搜索结果。具体来说,它不会按标题显示搜索。

终端显示此错误:

  src / app / app.component.ts(19,11)中的

ERROR:错误TS2551:类型“ AppComponent”上不存在属性“ posts”。您是说“发布”吗?

请帮助

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 :(得分:0)

您只需要添加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)
   }