The 'asObservable' property is not present on the type '() => any'.ts(2339)

Error: Property 'asObservable' does not exist on type '() => any'.ts(2339) Error: Property 'subscribe' does not exist on type 'Subscription'. Did you mean 'unsubscribe'?ts(2551) Error: Property 'subscribe' does not exist on type 'void'.ts(2339) Here is the code for my data service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { BehaviorSubject } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class DataService {
gifs = new BehaviorSubject<any>([]);
  constructor(private http: HttpClient) { }
  getTrendingGifs(){
    return this.http.get(`https://api.giphy.com/v1/gifs/trending?api_key=%${environment.giphyApiKey}&limit=50`)
    .subscribe((response: any) => {
     this.gifs.next(response.data);
    });
  }
  searchGifs(gifName: string){
    return this.http.get(`https://api.giphy.com/v1/gifs/search?q=${gifName}&api_key=%${environment.giphyApiKey}&limit=50`)
    .subscribe((response: any) => {
      this.gifs.next(response.data);
     });
  }
 getGifs(){
    return this.getGifs.asObservable(); 
  }
}

This is my search component code:

export class SearchComponent implements OnInit {

  constructor(private dataService: DataService) { }

  ngOnInit(): void {
  }
  search(searchTerm: string){
    if (searchTerm !== ''){
      this.dataService.searchGifs(searchTerm)
      .subscribe((response: any) => {
        console.log('Search Data', response);
      });
    }

  }
}

Below is the content of my gifs component:

import { ThisReceiver } from '@angular/compiler';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { DataService } from '../data.service';

@Component({
  selector: 'app-gifs',
  templateUrl: './gifs.component.html',
  styleUrls: ['./gifs.component.css']
})
export class GifsComponent implements OnInit, OnDestroy {
  gifs: any[] = [];
  subscription: Subscription;

  constructor(private dataService: DataService) { }

  ngOnInit(): void {
    this.dataService.getTrendingGifs()
    this.subscription = this.dataService.getGifs()
     .subscribe((response: any) => {
     this.gifs = response;
     });
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
    
  }

}

Answer №1

In response to @akotech's comment, it appears that there is a typo in your code snippet. Instead of:

return this.getGifs.asObservable();

The correct line should be:

return this.gifs.asObservable();

Additionally, the method you are using to retrieve and populate data from the server may result in memory leaks. It would be better to subscribe to the response at the component level and then destroy that subscription when the component is no longer needed.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class DataService {

  constructor(private http: HttpClient) { }

public getTrendingGifs(){
    return this.http.get(`https://api.giphy.com/v1/gifs/trending?api_key=%${environment.giphyApiKey}&limit=50`)
  }

 
public searchGifs(gifName: string){
    return this.http.get(`https://api.giphy.com/v1/gifs/search?q=${gifName}&api_key=%${environment.giphyApiKey}&limit=50`)
  }

}

Component:

import { OnDestroy, OnInit } from '@angular/core';
import { takeUntil } from 'rxjs/operators';

export class SearchComponent implements OnInit, OnDestroy {
  public destroy$: Subject<boolean> = new Subject<boolean>();

  constructor(private dataService: DataService) { }

  ngOnInit(): void {}

      search(searchTerm: string){
        if (!searchTerm || searchTerm == '') return;
          this.dataService.searchGifs(searchTerm)
          .pipe(takeUntil(this.destroy$))
          .subscribe((response: any) => {
            console.log('Search Data', response);
          });
        
      }

 ngOnDestroy() {
      this.destroy$.next(true);
      this.destroy$.unsubscribe();
  }

}

And:

import { ThisReceiver } from '@angular/compiler';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { DataService } from '../data.service';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-gifs',
  templateUrl: './gifs.component.html',
  styleUrls: ['./gifs.component.css']
})
export class GifsComponent implements OnInit, OnDestroy {
  public destroy$: Subject<boolean> = new Subject<boolean>();

  gifs: any[] = [];
  

  constructor(private dataService: DataService) { }

  ngOnInit(): void {
    
    this.dataService.getTrendingGifs()
     .pipe(takeUntil(this.destroy$))
     .subscribe((response: any) => {
     this.gifs = response;
     });

  }

  ngOnDestroy() {
     this.destroy$.next(true);
     this.destroy$.unsubscribe();
  }

}

In conclusion, unless you have specific requirements necessitating its use, you can avoid using BehaviorSubject for now.

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

Issues with implementing AddEventListener in InAppBrowser on IONIC 2

I am currently working on implementing AddeventListener to listen for 'Exit' and 'LoadStart' events in InAppBrowser within IONIC2. Here is my HTML: <button (click)="browsersystem('https://www.google.com')" > Visit URL& ...

Tips for effectively hydrating Redux state in Next.js upon page refresh?

I'm experiencing an issue with hydrating user data from local storage upon app reload or page refresh. My project utilizes NextJS for the frontend, and for managing state across the application I rely on redux-toolkit and next-redux-wrapper. Upon us ...

The error message "Unable to adjust headers once they have been sent. Angular Universal ExpressJS" appears

I am trying to implement a 404 error response in my Angular 5 component with server-side rendering. In my server.js file, I have set up the following: app.engine('html', (_, options, callback) => { let engine = ngExpressEngine({ bootst ...

"Create a separate function for the pipeable operator in RXJS for enhanced code

After working on some code, I came up with the following implementation this.form.valueChanges.pipe( take(1), map(val => // doSomething), exhaustMap(val => // someInner observable logic return of({someValue}) ) ).subscrib ...

Tips for utilizing chodorowicz / ts-debounce effectively

Looking to utilize the debounce function provided by the ts-debounce package (available at here) in my typescript project. However, struggling to find a concrete example of its usage in typescript. Would greatly appreciate any help or guidance on this ma ...

Make sure that every component in create-react-app includes an import for react so that it can be properly

Currently, I am working on a TypeScript project based on create-react-app which serves as the foundation for a React component that I plan to release as a standalone package. However, when using this package externally, I need to ensure that import React ...

The NestJs provider fails to inject and throws an error stating that this.iGalleryRepository.addImage is not a recognized function

I'm currently working on developing a NestJS TypeScript backend application that interacts with MySQL as its database, following the principles of clean architecture. My implementation includes JWT and Authorization features. However, I seem to be enc ...

Creating a dynamic columns property for Mat-Grid-List

Is it possible to create a Mat-Grid-List where the number of columns can be dynamically changed based on the width of the container? Here is an example: <mat-grid-list [cols]="getAttachmentColumns()" rowHeight="100px" style="width: 100%;"> <mat ...

What steps should be followed to effectively incorporate Google Fonts into a Material UI custom theme for typography in a React/TypeScript project

Hey there, I'm currently working on incorporating Google fonts into a custom Material UI theme as the global font. However, I'm facing an issue where the font-weight setting is not being applied. It seems to only display the normal weight of 400. ...

Guidelines for creating a masterpage and details page layout in Angular 6

In my app.component.html file, I have the following code: <div style="text-align:center"> <h1> Welcome to {{ title }}! </h1> </div> <div> <p-menu [model]="items"></p-menu> </div> Below is the code ...

Using parametric types as type arguments for other types in TypeScript or Flow programming languages

Consider the various types showcased for demonstration: type TranslateToEnglish<A extends string> = A extends "1" ? "one" : A extends "2" ? "two" : A extends "3" ? "three" : "e ...

Error in Angular2 routes: Unable to access the 'forRoot' property

angular2 rc.5 I encountered a problem with TypeError: Cannot read property 'forRoot' of undefined(…) after investigating, I discovered that RouterModule is appearing as undefined during execution. This is my app.route.ts: import {Routes, Rou ...

include the ReactToastify.css file in your project using the import statement

Error in file path C:\Users\User\Documents\GitHub\zampliasurveys_frontend\node_modules\react-toastify\dist\ReactToastify.css:1 ({"Object.":function(module,exports,require,__dirname,__filename,jest){:ro ...

Can an Angular Application be created in Azure without using an App Service Plan?

Our client has chosen Azure for their custom app development, utilizing API App for the backend and Angular for the front end. Interestingly, they have opted to not use an App Service Plan for the front end. Can anyone provide insight on how an Angular f ...

Angular 5: How to Calculate the Sum of Two Numbers and Handle NaN Output

I have encountered an issue where I am trying to multiply two numbers and add another number, but the output is displaying as NaN. How can I troubleshoot and solve this problem? Below is the code snippet: medicines = [new Medicine()]; this.sum = 0;// su ...

Methods of obtaining the array size using interpolation in Angular2?

Is there a way to inquire about the size of an array in Angular 2 when it is used within a component? For instance, consider the following: users : User[]; where export class User { id : number; firstName : String; lastName : String; userName ...

Adding a declaration file to a package that relies on an external declaration file can be achieved by following these

In the process of developing a library that relies on another package lacking a declaration file in its npm package, I have successfully installed the necessary declaration file with typings. Everything seems to be working well. Yet, the question remains: ...

The operation of assigning the value to the property 'baseUrl' of an undefined object cannot be executed

I recently created a JavaScript client using NSWAG from an ASP .NET Rest API. However, I am encountering some errors when attempting to call an API method. The specific error message I am receiving is: TypeError: Cannot set property 'baseUrl' of ...

Error Encountered: White screen issue affecting Ionic 6 / Angular 14 app running on Android 6.1 device without Google Mobile

After successfully deploying my new Ionic 6 / Android 14 app on multiple devices, I encountered a problem with one specific device - a Zebra ET50 running Android 6.1 without Google Mobile Services. The app fails to load and only shows a white screen. I no ...

The Validator.js module cannot be located - Unable to resolve 'http' in the client

Struggling with integrating the amadeus-node package into an angular 10 project. When I add the following line: const Amadeus = require('amadeus'); I encounter this error: ERROR in ./node_modules/amadeus/lib/amadeus/client/validator.js Module ...