The type 'Observable<{}>' cannot be assigned to the type 'Observable'

Before I begin, let me say that I have come across many similar questions with the same issue, but for some reason, I can't solve mine.

My setup is quite simple - a basic service and component. I'm closely following the angular2 hero tutorial. Below is my code:

location.ts


export class Location {
    name: string;
    type: string;
    c: string;
    zmw: string;
    tz: string;
    tzs: string;
    l: string;
    ll: string;
    lat: string;
    lon: string;
}

location-search.service.ts


import { Injectable }       from '@angular/core';
import { Http, Response }   from '@angular/http';
import { Observable }       from 'rxjs';

import { Location }         from './location';

@Injectable()
export class LocationSearchService {
    constructor(private http: Http) {}

    search(term: string): Observable<Location[]> {
        return this.http
            .get(`api_url_i've_removed`)
            .map((r: Response) => r.json().data as Location[]);
    }
}

location-search.component.ts


import { Component, OnInit }    from '@angular/core';
import { Router }               from '@angular/router';
import { Observable }           from 'rxjs/Observable';
import { Subject }              from 'rxjs/Subject';

import { LocationSearchService }    from './location-search.service';
import { Location }                 from './location';

@Component({
    selector: 'location-search',
    templateUrl: 'location-search.component.html',
    styleUrls: ['assets/styles.css'],
    providers: [ LocationSearchService ]
})

export class LocationSearchComponent implements OnInit {
    locations: Observable<Location[]>;
    private searchTerms = new Subject<string>();

    constructor(
        private locationSearchService: LocationSearchService,
        private router: Router) {}

    search(term: string): void {
        this.searchTerms.next(term);
    }

    ngOnInit(): void {
        this.locations = this.searchTerms // <- ERROR HERE
            .debounceTime(300)
            .distinctUntilChanged()
            .switchMap(term => term
                ? this.locationSearchService.search(term)
                : Observable.of<Location[]>([]))
            .catch(error => {
                console.log(error);
                return Observable.of<Location[]>([]);
            })
    }
}

I am encountering this error:


Type 'Observable<{}>' is not assignable to type 'Observable<Location[]>'.at line 29 col 9

Can you spot any obvious mistakes? Your help is greatly appreciated.

Answer №1

I faced a similar issue before, struggling with it a few times myself!

It seems to be related to the .switchMap() function. I'm not sure if it's a TypeScript problem or something else.. Maybe it has to do with the typings file being faulty.

The solution involves casting as shown below:

ngOnInit(): void {
    this.locations = <Observable<Location[]>>this.searchTerms // <- ERROR HERE
        .debounceTime(300)
        .distinctUntilChanged()
        .switchMap(term => term
            ? this.locationSearchService.search(term)
            : Observable.of<Location[]>([]))
        .catch(error => {
            console.log(error);
            return Observable.of<Location[]>([]);
        })
}

Alternatively, you can also use your functions switchMap() and catch() with type declarations like this:

ngOnInit(): void {
    this.locations = this.searchTerms // <- ERROR HERE
        .debounceTime(300)
        .distinctUntilChanged()
        .switchMap<Observable<Location[]>>(term => term
            ? this.locationSearchService.search(term)
            : Observable.of<Location[]>([]))
        .catch<Observable<Location[]>>(error => {
            console.log(error);
            return Observable.of<Location[]>([]);
        })
}

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

I can't decide which one to choose, "ngx-bootstrap" or "@ng-bootstrap/ng-bootstrap."

Currently, I am in the process of deciding whether to use Bootstrap 4 with angular 4 for my upcoming project. However, I find myself torn between choosing npm install --save @ng-bootstrap/ng-bootstrap or npm install ngx-bootstrap --save. Could someone pl ...

Sharing the input value with a service in Angular 4

I am a beginner when it comes to Angular 4. I currently have a variable named "md_id" which is connected to the view in the following way. HTML: <tr *ngFor="let item of driverData"> <td class="align-ri ...

Creating a responsive d3 gauge chart: A step-by-step guide

Need assistance resizing the d3 gauge chart. Check out the Stackblitz code for reference. I've attempted the following: .attr("preserveAspectRatio", "xMinYMin meet") as well as window.addEventListener("resize", this.draw); ...

Sending data between a Grandchild component and its Parent component

In my Angular 8 project, I have multiple components structured in the following way: Parent 1 > Child 1 > ... > N Grandchild 1 Parent 2 > Child 2 > ... > N Grandchild 2 There might be other components between Child X and N Grandchild ...

Tips for incorporating nonce or sha into the connect-src directive in Content Security Policy (CSP)

Can a nonce be used in an API request to make sure that the connect-src in CSP doesn't flag it as a malicious address? It appears that nonce can only be used in script-src or style-src, not in connect-src. So far, I have only been able to list URLs ...

Invoking a method in a derived class upon completion of asynchronous logic within the base class

Currently, I am in the process of building an Angular application. One aspect of my project involves a class that extends a base class. While this approach may not be ideal, I am curious to know what would be the best practice for BaseClass to trigger me ...

Learn how to implement autofocus for an ng-select element within a bootstrap modal

When working with ng-select inside a modal, I am facing an issue with setting autofocus. While I am able to add focus for the input field within the modal, the same approach doesn't work for ng-select. Can anyone provide guidance on how to set focus f ...

Previewing multiple selected files in Angular interface

As a newcomer to Angular, I am currently working on a feature that involves selecting multiple files and displaying their previews before uploading them to the server. While my code works correctly when individual files are selected one at a time, it fail ...

The error message "NullInjectorError: No provider for HTTP!" is generated by the ionic-native/http module

Currently working with ionic 3.2 and angular. To install the HTTP module (https://ionicframework.com/docs/native/http/), I used the following commands: ionic cordova plugin add cordova-plugin-advanced-http npm install --save @ionic-native/http In my scri ...

Angular: Display an element above and in relation to a button

Before I dive in, let me just mention that I have searched extensively for a solution to my problem without much luck. The issue is describing exactly what I'm trying to accomplish in a way that yields relevant search results. If you're interest ...

Using MongoDB to swap out an object within an array

I'm facing a challenge in replacing/updating an entire object in an array with its latest values, and I can't seem to make it work. Here's how the database looks: (Please note that there is only one main object in this collection) { ...

The error encountered states that in the Angular typescript method, the term "x" is not recognized as a

In my codebase, I have an entity named Epic which contains a method called pendingTasks() within a class. import { Solution } from '../solutions.model'; import { PortfolioKanban } from '../kanban/portfolio-kanban.model'; import { Kanban ...

How can I utilize a lookup type when dealing with a member of a static class?

I have a Typescript class where I defined a class member for a specific type in the following way: export class AccordionSection extends Component { } export class Accordion extends Component<AccordionProperties> { public static Section = Acco ...

Align the ion content (or text or label) to the center vertically

I am striving to achieve a similar look as shown in the following images: https://i.sstatic.net/YFMay.png However, I am currently at this stage: https://i.sstatic.net/ZvpBV.png Please note that the first image showcases a bootstrap form, while the seco ...

Invoke a function in Angular when the value of a textarea is altered using JavaScript

Currently, I am working with angular and need to trigger my function codeInputChanged() each time the content of a textarea is modified either manually or programmatically using JavaScript. This is how my HTML for the textarea appears: <textarea class ...

Angular Universal - Preserving server-side requests for efficient client-side caching

After reading multiple articles on caching data for client in angular universal apps, I am still puzzled about how the data is transferred from server to the client. Should I inject the JSON into pre-rendered HTML or could there be another method that I&ap ...

Fetch the current user using JHipster

Currently, I am developing a JHipster application that includes a Study entity which is related to the User entity in a many-to-one relationship (meaning one user can have multiple studies). My goal is to make the selection of the current logged-in user au ...

Allow TypeScript function parameters to accept multiple elements from an enumeration

Enumerating my options. export enum Selection { CHOICE_ONE = 'one', CHOICE_TWO = 'two', CHOICE_THREE = 'three', CHOICE_FOUR = 'four', } I am looking to design a function that accepts an array, but re ...

Creating dynamic class fields when ngOnInit() is called in Angular

I am trying to dynamically create variables in a class to store values and use them in ngModel and other places. I understand that I can assign values to variables in the ngOnInit() function like this: export class Component implements OnInit{ name: st ...

Prevent API requests with a toggle button in RxJS to start and stop calls

I have been diving into Rxjs and managed to put together a simple slideshow that updates the images every 5 seconds after clicking the start button. However, I am struggling to figure out how to pause/stop the API fetching process once the button is clicke ...