Unable to set Object[] as an Observable<Object[]>

Currently in the midst of tackling an Angular 4 project, I have been able to troubleshoot most issues on my own so far. However, there is one error that has me stumped.

I am attempting to use *ngFor (async) to showcase a list of Observable objects. Despite feeling confident that my service is returning an Observable< Course[] >, I keep encountering the error "Cannot assign Course[] to Observable< Course[] >".

In course-list.component.ts:

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { CourseCardComponent } from '../course-card/course-card.component';
import { CourseCardService } from '../course-card/course-card.service';
import { CourseCard } from '../course-card/course-card.model';
import { Observable }     from 'rxjs/Observable';

@Component({
  selector: 'app-course-list',
  templateUrl: './course-list.component.html',
  styleUrls: ['./course-list.component.css']
})
export class CourseListComponent implements OnInit {
  courseCards : Observable<CourseCard[]>;
  loaded = false;

  constructor(private http:Http, private coursecardService:CourseCardService) { }

  ngOnInit() {
    this.coursecardService.getCourses()
    .subscribe(
      courses => {
        this.courseCards = courses;
        console.log(this.courseCards);
        this.loaded = true;
      },
      err => {
        console.log("Error", err);
      }
    )
  }
}

In course-card.service.ts:

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

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { CourseCard } from './course-card.model';

@Injectable()
export class CourseCardService {
    // Receives this JSON data:
    // [{"firstName":"Jane"},{"firstName":"John"}]
    private URL = '/api/getcourses';

    constructor (private http: Http) {}

    getCourses(): Observable<CourseCard[]> {
        return this.http.get(this.URL)
            .map((response) => {
            let data = response.text() ? response.json():[{}];
                if(data) {
                    return data;
                }
            }
        )
        .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
    }
}

And the HTML code for the course-list component:

Courses
<ul>
  <li *ngFor="let course of courses|async">
    <app-course-card [name]='course.name' [wordcount]=0></app-course-card>
  </li>
</ul>

Answer №1

In this section, an Observable<CourseCard[]> is returned:

this.coursecardService.getCourses()

Instead of manually subscribing to it and dealing with the type mismatch when trying to assign this.courseCards = courses;, you can utilize the async pipe to handle the subscription for you. Update your code to:

ngOnInit() {
  this.courseCards = this.coursecardService.getCourses();
}

Answer №2

After doing some further research on the .subscribe method, I discovered that it actually returns a subscription object. To fix this issue, all I had to do was modify my code as shown below:

ngOnInit() {
    this.courseCards = this.coursecardService.getCourses();
  }

Answer №3

Are you sure the name of your list properties is correct? Should it be let course of courses or should it actually be let course of courseCards?

   <ul>
      <li *ngFor="let course of courseCards|async">
        <app-course-card [name]='course.name' [wordcount]=0></app-course-card>
      </li>
    </ul>

Answer №4

Here's a different approach:

fetchCourses(): Observable<CourseCard[]> {
    return this.http.get(this.API_URL)
        .map((res) => <CourseCard[]>res.json())
        .catch((err: any) => Observable.throw(err.json().error || 'Encountered server issue'));
}

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

Using regex to pick out every instance of zero that comes before a numerical value

I am currently utilizing PowerRename, a tool that allows for regex usage to select portions of filenames for replacement. My goal is to tidy up some filenames by removing the preceding zeroes before a number in the file name (replacing them with nothing). ...

How can you display a loading indicator after a delay using Observables, but make sure to cancel it if the loading is completed

Within my customer-detail component, I have implemented code that achieves the desired outcome. However, I believe there might be a more reactive and observable way to approach this task. Instead of using an if statement to set this.isLoading = true;, is ...

Creating a paginated table with Nextjs, Prisma, and SWR: A step-by-step guide

I am attempting to set up a paginated table utilizing Nextjs, Prisma, and SWR. The table will display a list of invoices sorted by their ID. Here is an example of what it would look like: https://i.sstatic.net/WymoH.png To fetch all the data to the api r ...

Showcasing certain elements as the user scrolls

Looking for a way to display an element (such as a div) when the user scrolls without using JQuery? Here's an example that tries to achieve this: var scroll = document.body.scrollTop; var divLis = document.querySelectorAll("div"); for(let i = 0; i ...

String defines the type

I came across the following code snippet in some external sources that I intend to incorporate into my project: const INIT: 'jsonforms/INIT' = 'jsonforms/INIT' Can someone explain what it means to define a type with a string like INIT ...

Exclude a specific tag from a div in JavaScript

I need help selecting the text within an alert in JavaScript, excluding the <a> tag... <div id="addCompaniesModal" > <div class="alertBox costumAlertBox" style="display:inline-block;"> <div class="alert alert-block alert- ...

Unable to include a controller in an Angular project generated by Yeoman

I'm currently utilizing the Yeoman scaffolding to develop an Angular application and I'm encountering some difficulties when trying to add a controller. The about and main controllers are automatically added and function properly. However, whenev ...

Sorting objects with Javascript

users[usernames] = { userName : username, userId : id, userStatuINT : statu, userMobilemi : mobile, }; Console log : console log(JSON stringify(data)); Output : { "Guest-77": {"userName":"Jack","userId": ...

The carousel spun around, each section moving to the side on its own

One issue I'm facing is that on my page, I have multiple carousel rows. However, when I click on the "next" or "prev" button to navigate through the items in the carousel, it affects all carousels instead of just the one I clicked on. I've attem ...

Using External APIs in React: A Guide

Recently, I created a React app using the npm module 'create-react-app' I ran into an issue where I needed to call an external API from api.example.com, but found that Axios was making requests to localhost instead of the external API. Here is ...

Unexpected results observed in enumerators within typescript

Could someone clarify the results that I am seeing from the code below? enum days { sun = 1, mon = 0, tues }; console.log(days[1]); // outputs tues // should output -- mon console.log(days[0]); // outputs mon // should output -- sun Furthermore, how ...

In the latest version of Angular, Angular13, there seems to be an issue with the minimum length validation not functioning correctly within a FormControl of

When working with TypeScript, the function initializeForm() is called first inside ngOnInit. initializeForm() { this.rangeMappingForm = this.formBuilder.group({ mappingsList: this.formBuilder.array([], Validators.required) }); } After that ...

``Is there a specific location where I can access the Microsoft Azure msal sign-up feature within Angular

My current Angular version is 5.2.0 and I am struggling to find a tutorial on how to incorporate Azure MSAL for new user sign-up using a Microsoft account. If anyone has any resources or examples on how to achieve this integration without having to update ...

Implementing a codeigniter delete confirmation box with Javascript

I have tried numerous solutions on this site, but nothing seems to be working for me. I am trying to implement a pop-up window confirmation before deleting my data. Here is the code I am using: <a href="<?php echo site_url('admin/barang/delet ...

Optimizing the performance of "document.createElement"

When attempting to display multiple rows of data in a popup using a for loop, I initially utilized text strings to create and append the div elements. However, I discovered that using document.createElement resulted in a 20% improvement in performance. D ...

Is it feasible to have pagination and dynamic data in a Google Chart?

I am working on a marketing project where I plan to incorporate a Google Donut Chart with pagination using AJAX. However, I have encountered an issue where the chart does not load when moving to the next page. It only displays data upon initial loading. Be ...

What are the steps to execute PhantomJS on a client machine?

I have implemented an HTML to PDF converter that utilizes phantomjs, following this method: npm install -g html-pdf var fs = require('fs'); var pdf = require('html-pdf'); var html = fs.readFileSync('./test/businesscard.html' ...

Having Trouble Assigning Three JS Material to Mesh Object

This is the code snippet for creating a glass material: const glassMaterial = new THREE.MeshPhysicalMaterial( { // color: 0xffffff, metalness: 0.25, roughness: 0, transmission: 1.0 color: 0xffffff, metalness: 0.25, roughness: 0, transmi ...

Adding new rows to an ng-repeat table in AngularJS with unique controls for each row, distinct from those

I have a table filled with JSON data using ng-repeat, similar to the example shown here: https://i.sstatic.net/Ffjuy.png Now, I am looking to insert new rows at the top of the table by clicking a button. However, these additional rows should contain edit ...

Javascript has ceased functioning on the current server, however it is operational on a different

Need a hand with this tricky issue. The company I'm with has its own website. I've been updating pages on the site for the past few days. After finishing my updates and trying to upload the site, all of a sudden, the JavaScript stopped working. ...