Error message: Incompatible types - Cannot assign type 'Observable<{}>' from Angular 4 to type 'Observable<{}>' in Angular 5

I recently updated my Angular version from 4 to 5 and encountered a type error.

The type 'Observable<{}>' is not compatible with the type 'Observable<Device[]>'

I am struggling to find a solution for this issue. I came across a similar post here: Type 'Observable<any>' is not assignable to type '[]'. However, I am unable to apply the solution to my problem.

Here's the content of the ts file:

import {Component, OnInit} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import {ListDeviceService} from '../../services/list-device.service';

interface Device {
  name: string;
  id: string;
}

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html'
})
export class ProductComponent implements OnInit {

  devices: Observable<Device[]>;

  constructor(private listDeviceService: ListDeviceService) {
  }

  ngOnInit() {
    const scope = this;

    this.listDeviceService.getMyDevices().then(function (data) {
      scope.devices = Observable.of(data);
    });
  }
}

Below is the code for the list-device.service:

import {Injectable} from '@angular/core';
import {AuthenticationService} from '../services/authentication.service';

@Injectable()
export class ListDeviceService {

  constructor(private authenticationService: AuthenticationService) {
  }

  getMyDevices() {
    const scope = this;
    return new Promise((resolve, reject) => {
      const token = this.authenticationService.getToken();
      const devicesPr = this.authenticationService.getPartsAPI().listDevices({auth: token});
      devicesPr.then(
        function (devices) {
          console.log('list', devices.body);
          resolve(devices.body);
        },
        function (err) {
          reject(err);
        }
      );
    });
  }
}

Lastly, here's the package.json file:

"dependencies": {
    "@angular/animations": "^5.0.0",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/platform-server": "^5.0.0",
    ...
  },
  "devDependencies": {
    "@angular/cli": "1.3.2",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/language-service": "^4.2.4",
    ...
  }

Answer №1

With typescript version 2.4.2 and above, the typing rules have become more stringent, requiring you to be more precise with your typings.

If you need to define the function getMyDevices(), it should be done as follows:

 getMyDevices(): Promise<Device[]> {... // fetching the data ...}

Alternatively, if the return type is any, you might be able to use this approach:

this.listDeviceService.getMyDevices().then(function (data: Device[]) {
  scope.devices = Observable.of(data);
});

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

Before loading a deep link, use pre-CanActivate or pre-CanLoad

In my current project, I am faced with a challenging task of transitioning from Adobe Flash & Flex applications on a ColdFusion 11 backend to Angular applications. The expectation is that users will already be logged in and have an active session before a ...

Tips for aligning the text horizontally in an input field with a neighboring element

Hello amazing community, I'm searching for a neat way to align the text of an element horizontally with that of an Angular Material input field. Here is the code I am using: <div style="display: flex"> <div>Greeting: </div> ...

Is it possible to spread an empty array in JavaScript?

Whenever I run the code below, I encounter the error message Uncaught SyntaxError: expected expression, got '...': [1,2,3, (true ? 4 : ...[])] I'm wondering if spreading an empty array in that manner is allowed? ...

Leveraging angular-cli to compile a library that can be easily integrated into multiple projects

Let me provide some context: I set up an angular-cli (beta 17) project for my organization that includes multiple components I want to share with other Angular 2 projects within the organization. Initially, I kept it simple by using npm to install the Gi ...

Ways to eliminate the need for margin adjustments when buttons are shown in Responsive mode

I am currently utilizing Angular 14 along with SCSS Within a dialog component, I have two buttons displayed horizontally. The first button displays the text I am feeling lucky, while the second button displays Not lucky. There should be a separation of 20 ...

What is the proper method for typing unidentified exports that are to be used in TypeScript through named imports?

Currently, I am developing an NPM package that takes the process.env, transforms it, and then exports the transformed environment for easier usage. The module is structured like this: const transformedEnv = transform(process.env) module.exports = transf ...

What is the most straightforward way to make a property observable in terms of syntax?

There are countless tutorials out there demonstrating various ways to implement observables in Angular, but many of them are too complex for my needs. Some are outdated and no longer applicable. Let's assume I have a service with a single property ca ...

Challenges with TypeScript's typeof operator and instantiation of classess

Discussing the scenario of a map setup: const map = { a: ClassA, b: ClassB, c: ClassC, } The purpose of this map is to link different classes together. There exists a function that returns an instance of a class based on a key in the map ...

Leverage the extended properties of Express.js's Request's generic arguments

I am currently working on extending the Request type to include a property that relies on the request body. However, I am facing an issue where the generic in catchAsync is not being correctly applied and always defaults to any instead of the specified gen ...

Error encountered in NextJS API: "TypeError: res.status is not a function"

Background In my development environment, I am using NextJS v11.1.1-canary.11, React v17.0.2, and Typescript v4.3.5. To set up a basic API endpoint following the guidelines from NextJS Typescript documentation, I created a file named login.tsx in the pag ...

Clicking on an icon to initiate rotation (Material UI)

Is there a way to toggle the rotation of an icon (IconButton) based on the visibility of a Collapse component? I want it to point down when the Collapse is hidden and up when it's shown. const [expanded, setExpanded] = useState<boolean>(false); ...

Is it necessary to upload items individually using Angular 7 and Asp.net?

I'm encountering an issue where I am trying to send objects to my server, but the objects received have null values. Here is a snippet of the backend code: // Signature public IActionResult Save(string num, string pat, string token, [FromBody]DataC ...

Binding objects and properties from Angular2/Typescript to a template

Disclaimer: Seeking insight on the correct approach or any additional information _____________________________________________________________________ ANGULAR1 When working with angular1, we had the option to define our objects in the following ma ...

Utilizing Angular 2 Services for Seamless Data Sharing Among Components

I am currently working on implementing a service that will help me define a shared resource called client across multiple views. The process involves selecting the client from an index and then setting it up as follows: itemTapped(event, client) { this. ...

Exploring the depths of Rx.ReplaySubject: Techniques for delaying the `next()` event

Confused Mind: Either I'm mistaken, or the whiskey is starting to take effect. (I can't rule out the possibility that I'm just going crazy. Apologies for that.) Assumption: My assumption was that ReplaySubject would emit a single value eve ...

Unable to retrieve data header in the Angular 10 build version

I have a code snippet for an HTTP request: return this.http.post<any>(this.path.userRoot + '/logIn/random', body, { withCredentials: true, responseType: "json", observe: 'respon ...

Utilizing asynchronous methods within setup() in @vue-composition

<script lang="ts"> import { createComponent } from "@vue/composition-api"; import { SplashPage } from "../../lib/vue-viewmodels"; export default createComponent({ async setup(props, context) { await SplashPage.init(2000, context.root.$router, ...

Lazy loading a child component in Angular 8: A step-by-step guide

In my project, I have a complex component that consists of multiple modals (NgbModal). These modals are connected to various child components. My goal is to implement lazy loading for these child components. Dashboard Module | |--> Dashboa ...

Ionic/Angular 2: Issue accessing object in the Page1 class - error caused by: Unable to retrieve the 'name' property as it is undefined

Currently, I am working on developing an application using Ionic and below is the code snippet: <ion-header> <ion-navbar> <button ion-button menuToggle> <ion-icon name="menu"></ion-icon> </button> &l ...

Angular with D3 - Semi-Circle Graph Color Order

Can someone assist me with setting chart colors? I am currently using d3.js in angular to create a half pie chart. I would like to divide it into 3 portions, each represented by a different color. The goal is to assign 3 specific colors to certain ranges. ...