An issue has been encountered with code: "ERROR error TS2551: The property 'posts' is not found"

https://i.sstatic.net/VRIsT.pngI've been attempting to run it, but it's unable to generate search results. Specifically, it's not showing search by title.

Terminal is displaying this error:

ERROR in src/app/app.component.ts(19,11): error TS2551: Property 'posts' does not exist on type 'AppComponent'. Did you mean 'post'?

Seeking assistance

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>

SearchBarComponent.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 = '';
}


}

Answer №1

In order to update the app.component.ts file with a new type, simply add posts: any; or any other desired type under post: Post[];

To execute a search, you will need to switch this.post to this.posts within the getFilteredExpenseList() function

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

To implement these changes, ensure that you have added the appropriate types and made the necessary adjustments for searching functions in your code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting error messages with Angular 2 HttpClient response payload

Currently, I am implementing the latest version (4.3) of HttpClient in angular to handle data POST requests to my backend server: this.httpClient.post<View>(`/path`, data).subscribe( (view: View) => console.log("Success"), (error: HttpErrorRe ...

Tips for setting up a system where PHP serves as the backend and Angular acts as the

I am working on a project that utilizes Angular as the front end and PHP as the back end. Both are installed in separate domains, with the PHP project fully completed and operational. I have created an API in PHP which I plan to call from Angular. My ques ...

Is it possible to retrieve a union type property as an array of values in order to conduct a flexible type validation process?

Currently, my code looks something like this: interface Apple { type: 'Apple' } interface Banana { type: 'Banana' } interface Coconut { type: 'Coconut' } type Fruit = Apple | Banana | Coconut type AppleOrBanana = App ...

Adjust the starting color of a mat-input in Angular 9

I am encountering an issue with the styling of a standard matInput field within a mat-form-field, all contained within a [formGroup] div. The dark background of the parent element is causing visibility problems with the default dark text color of the input ...

Using Fixed Patterns and Combining Types in an Interface

Presently, I am working with this interface: export interface User{ name: string birthday: number | Timestamp ... } When strictTemplates:false is enabled, I have no issue using this interface for server data retrieval with the birthday parameter in ...

Setting headers in Angular 2: A step-by-step guide

Here are the headers I am using: var headers = new HttpHeaders(); headers.set('Content-Type', 'application/json'); headers.set('X-Quikr-App-Id', '1087'); headers.set('X-Quikr-Token-Id&ap ...

Troubleshooting the dependency problem with @config-plugins/react-native-ble-plx

I am currently trying to install a package in order to utilize react-native-ble-plx on an expo app. However, I am encountering a dependency issue. Can anyone provide assistance with the following: npx expo install › Installing using npm > npm install ...

Modifying tooltip format in React ApexChart from dots to commas

I am in the process of creating an app targeted towards German users, who traditionally use commas (20,00) instead of dots (20.00) for numbers. I am using react-apexcharts and struggling to figure out how to replace the dots with commas in both my chart an ...

What steps can I take to avoid an invalid operation on a potentially null reference in typescript?

Take a look at this scenario where the variable a can potentially be null, and is explicitly defined as such. Even when strict null checks are enabled, TypeScript does not flag a possible issue in this situation - let a: string | null = "hello" function ...

I am struggling to save the value from my input field into the app.component.ts file

Having some trouble storing an input from my form into a property. After submitting, the console.log is showing undefined in the console. I've experimented with different variations, but none seem to be working as intended. <form> <input #i ...

Updating templates using Angular 2 observables for change detection

Looking to optimize performance, I am exploring the implementation of manual change detection on my components. The app structure is as follows: App -> Book(s) -> Page(s) In the AppComponent, I subscribe to an observable and then utilize the "markF ...

Do ES6 features get transpiled into ES5 when utilized in TypeScript?

After implementing ES6 features such as template strings, arrow functions, and destructuring in a TypeScript file, I compile the code to regular JavaScript... Does the TypeScript compiler also compile the ES6 syntax, or do I need to utilize another compil ...

Create a chronological timeline based on data from a JSON object

Here is a JSON object generated by the backend: { "step1": { "approved": true, "approvalTime": "10-11-2021", "title": "title 1", "description": "description 1" ...

Angular automatically protects routes by default

In the application I've created, there is a requirement for most routes to be protected and accessible only when logged in. Is it feasible to implement a default route guard while also specifying certain routes that should remain open? ...

Exploring Angular2's ability to interpret directive templates using the ng-container

Recently delving into angular2, I ventured into creating dynamic forms and generating fields by following the guide provided in this URL. The result was as expected. The dynamic form component renders each field one by one using ng-container, like shown b ...

Unable to activate ngx-scrollbar RTL mode in my Angular application

I have been working on implementing Right-to-Left (RTL) support for scrolling using the ngx-scrollbar package in my Angular project. Unfortunately, I am facing an issue where the scrollbar does not seem to function correctly when in RTL mode. To add ngx-s ...

"Excel file becomes inaccessible after being downloaded from server using Lambda function with Node.js and Angular

My Nodejs code generates an excel file, which is then transformed based on client request. I am sending a request from an Angular frontend. The code utilizes exceljs to create the excel file. let [row] = await conn.execute( "Query& ...

Encountering a JSON error in Ionic 3 due to a circular structure conversion

Hello everyone, I am a beginner in Angular 2+ and Ionic 3. I am currently attempting to submit a login form from my Ionic 3 app to my ASP.NET Web API application for token-based authentication. However, I keep encountering the following error: converting c ...

When adjusting the window size with the <ion-split-pane>, both the menu and router outlet disappear

When I have two ion menus and one main content (router outlet) and resize the page or switch to mobile view, the page appears blank as if the content is missing. Here is the code: <ion-app> <ion-split-pane> <ion-menu side="start" me ...

Formatting database values in `where` conditions for strings in TypeORM: A simple guide

I am trying to utilize TypeORM's "exist" method in order to check if a name has already been inserted into the database. My issue is that I cannot determine whether the name was inserted in uppercase or lowercase, leading to potential false validatio ...