Search code examples
angularangular-httpclientangular15

Can't make http request with Angular 15


For some reason I can't get my Angular 15 app to send an http request. I'm used to an older version of Angular so I wonder if it's some configuration I'm missing or something. I also already added HttpClientModule under imports in app.module.ts. I know it's not the endpoint because I use that exact same url in my service in postman and it hits it no problem. What am I missing. I appreciate any help!

service:

import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class MainFeedService {
  baseUrl: string = 'http://localhost:3000';
  constructor(private http: HttpClient) {}

  getMainFeed(userId: string) {
    // const totalRecords = totalPosts ? totalPosts.toString() : undefined;
    const param = new HttpParams().set('userId', userId);

    const params = param;
    return this.http.get<{
      records: any;
      totalPosts: number;
    }>('http://localhost:3000/local/main-feed', { params });
  }
}

component:

import { Component } from '@angular/core';
import { takeUntil } from 'rxjs';
import { MainFeedService } from 'src/services/trades.service';

@Component({
  selector: 'app-main-feed',
  templateUrl: './main-feed.component.html',
  styleUrls: ['./main-feed.component.scss'],
})
export class MainFeedComponent {
  destroy: any;
  totalPosts = 0;
  userId = 'test';
  constructor(private mainFeedService: MainFeedService) {}

  ngOnInit() {
    this.mainFeedService
      .getMainFeed(this.userId)
      .pipe(takeUntil(this.destroy))
      .subscribe((res: any) => {
        console.log('RES', res);
      });
  }
}


Solution

  • destroy notifier observable is undefined by default. It should be defined with Subject

    destroy = new Subject();