How Subscribe functions independently in Angular without the need for Observable

I was trying to grasp the basics of Angular and HttpClient. Surprisingly, my code is actually working, but I'm struggling to comprehend why. In my quest for understanding, I delved into these two insightful links:

  1. How to properly subscribe to Angular HttpClient Observables?
  2. How to define Return Types for Functions in TypeScript

A YouTube video also caught my attention:

  1. Observable and Subscription in Angular 8 | Informative Tutorial in Hindi

From what I gathered, the syntax for HttpClient's GET method appears as follows:

get(url: string, options: {...}): Observable<any>

Hence, following the instructions provided in the video, I implemented it accordingly. Here's my first approach:

UserService

...
export class UserService {
  constructor(private _http: HttpClient) { }
  getAllUsers() {
    return this._http.get("https://jsonplaceholder.typicode.com/users"):Observable<any>;
  }
}

However, VSCode raised an error:

The value of type 'typeof Observable' cannot be called directly. Are you missing the 'new' keyword?

Interestingly, my code functions flawlessly even without explicitly mentioning Observable. Consider my second scenario:

...
export class UserService {
  constructor(private _http: HttpClient) { }
  getAllUsers() {
    return this._http.get("https://jsonplaceholder.typicode.com/users");
  }
}

Furthermore, here's the snippet from my component (applicable to both cases):

UserList

  users=[];

  constructor(private userService: UserService) { }

  ngOnInit() {  
    this.fetchAllUsers();  
  }

  fetchAllUsers() {
    this.userService.getAllEUsers().subscribe(
      res => {
        this.users.push(res)
      }
    );    
  }

If you could highlight any mistakes I've made in either case, I would greatly appreciate it. It seems like I might be unintentionally breaking some Angular conventions.

P.S.: Attached a screenshot from the tutorial on YouTube:

https://i.sstatic.net/EBSHK.png

Answer №1

Your code contains an error on the following line:

return this._http.get("https://jsonplaceholder.typicode.com/users"):Observable<any>;

To fix this issue, you need to update the method declaration like so:

getAllUsers(): Observable<any> {
  return this._http.get("https://jsonplaceholder.typicode.com/users");
}

If you need help with TypeScript basics, consider taking a refresher course here.

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 Ionic 3's ion-slide within an ion-list component causing functionality problems

My slide is not functioning properly within an ion-list. I placed it there because I am using infinite scroll and it does not scroll correctly when the slide is outside the list. Is there a way to make the slide work within the ion-list? <ion-list no ...

Refreshing the page is the only way to see the changes made by Angular's delete item function reflected

In my application, I am retrieving a table of users from an API. However, when I delete a user, the table does not update until I manually reload the page. This relates to the user service in my application. getUsers(): Observable<any> { return ...

Ignoring setTimeout() function within forEach() in Angular leads to issues

I am currently working on the frontend development of a Web Application using Angular. My task involves saving data from an array into a database by making repeated API calls until all the array data is processed. I implemented the use of setTimeout() in ...

What is the process for creating distinct templates for various devices such as mobile phones, desktops, and tablets using Angular?

I am working on an Angular 9 application. Currently, I have some mockups but the template appears differently on mobile compared to desktop. However, the data fetched from API calls is mostly similar for both platforms, with slight variations possible be ...

What are the best techniques for concentrating on a kendo maskedtextbox?

What is the correct way to set focus on the kendo-maskedtextbox in TypeScript after the view has initialized? The information provided in Telerik's example here is lacking in detail. ...

Invalidity of types occurs when dispatching data to redux

My reducer code is as follows: import { profileAPI } from '../api/api' import shortid from 'shortid' const ADD_POST = 'profile/ADD-POST' const SET_USER_PROFILE = 'profile/SET_USER_PROFILE' const SET_STATUS = 'p ...

What sets apart `tsc --build --clean` from `rm -rf *.js` command?

I'm curious about the tsc command with the arguments --build --clean, which is used to clean/remove the generated .js files from the Transpiler (tsc). What makes this command special or significant? If I simply need to delete all the .js files, I can ...

In Angular 5, when you reset a required form control in a reactive form, the required error message beneath the input field is not cleared

Within my template, there is a form that becomes visible when a button is clicked- <form [formGroup]="person" (ngSubmit)="onSubmitNewPerson()" #formDirective="ngForm"> <mat-form-field> < ...

connecting and linking template content with an Observable

I have a CRUD page that needs to be updated after every operation. I have implemented Observable and the CRUD functions (specifically Add and Delete) are working fine, but I need to manually refresh the page to see the changes reflected. After trying to ...

I have a Visual Studio 2019 solution that consists of two projects - one is an Angular project and the other is written in TypeScript. I have successfully configured

We are currently utilizing Visual Studio 2019 (not the VS Code version) for our project. Within this solution, we have multiple projects included. One of these projects contains Angular code that we compile using the traditional 'ng build' comma ...

How to detect a click event in any area of an Angular2

Hey there, I'm new to typescript and angular 2 and I've encountered an error in my code. Can someone lend me a hand in fixing this? import { Component, HostListener } from '@angular/core' export class TooltipComponent { public sh ...

Utilizing type guards in prop functions for conditional rendering within React TypeScript adds an extra layer

In my code, I am conditionally rendering a Button. However, I encountered an issue on line 7 where TypeScript is indicating that the first parameter of the exportExcel function may be null even though it should not be, considering the conditional render lo ...

Error: Pump 3.0.1 encountered an unexpected character { causing a syntax issue

At approximately 10:30 PST on September 10, 2024, my ng build command suddenly started throwing an error during the execution of ng build. I am aware that I am using an outdated build and the immediate solution may be to upgrade everything to the latest ...

Avoid using dot notation with objects and instead use `const` for declaring variables for more

interface obj { bar: string } function randomFunction() { let foo: obj = { bar: "" } foo.bar = "hip" } let snack: obj = { bar: "" } snack.bar = "hop" Upon transcompiling, a warning from tslint pops up: Identifier 'foo' is never reassi ...

What are the appropriate scenarios for extending and utilizing an abstract class in Angular?

@Component({ selector: 'my-component', template: `<ng-content></ng-content>`, providers: [ { provide: AbstractClass, useExisting: forwardRef(() => TargetComponent) } ] }) export class TargetComponent extends AbstractCla ...

Troubleshooting: Background images in SCSS file not appearing when using Webpack

Attempting to utilize webpack's sass-loader to load a .scss file that includes background images. Here is a snippet of the .scss code: .clouds_two { background: url(require("../../../images/cloud_two.png")); //no error, just not appearing //bac ...

What is the best way to transform an Observable<Observable<HttpEvent<any>>> into an Observable<HttpEvent<any>> within the Angular AuthInterceptor service?

export class AuthInterceptor implements HttpInterceptor { constructor(private usersService: UsersService){} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return this.usersService ...

Adjust the observable value from the mocked service dynamically for every test in Angular/Jasmine/Redux

I am working on a project where I need to write unit tests for a component that uses a service returning values exposed by ngrx selectors. In order to test different scenarios, I am using a mock of the service. However, I am facing challenges in getting th ...

Is it possible to install Shadcn ui for Vite + React using only JavaScript instead of TypeScript?

I'm encountering difficulties when attempting to install and use shadcn components in my Vite + React + Tailwind project. I followed the instructions provided in their documentation here, but it seems like it requires TypeScript to function properly? ...

How can I rename an event function in Angular 2?

Is it possible to dynamically change the function associated with an event? I attempted to do so like this: (click) = "{{myFunction}}" However, I encountered an error stating "Parser Error: Got interpolation ({{}}) where expression was expected". I am lo ...