Angular 8: Syncing Component Values with Service Updates

My Angular 8 project features two sibling components that utilize a service to manage restaurant data. One component displays a list of restaurants fetched from an api, while the other component filters the displayed restaurants based on user input. Despite using a service to handle restaurant data, I am facing an issue where the data is not being populated upon loading. Below is the code for my components and service:

Restaurant.service.ts

@Injectable()
export class EatstreetService {

  radius;
  address;
  public restaurants: BehaviorSubject<any> = new BehaviorSubject<any>(null);

  constructor(private httpClient: HttpClient) { }

  public setRestaurant(){
    let params = new HttpParams();
    params = params.append('method', 'delivery');
    params = params.append('pickup-radius', this.radius);
    params = params.append('street-address', this.address);
    params = params.append('access-token', this.token)
    this.restaurants.next(this.httpClient.get(`https://api.com/publicapi/v1/restaurant/search`, {params}))
  }


  public getRestaurant(): Observable<any>{

    return this.restaurants.asObservable();
  }
}

RestaurantFilter.component.ts

export class LocationComponent implements OnInit {
  restaurants;
  radius;
  address;

  constructor(private eatstreetService: EatstreetService) { }

  setRestaurants() {
    this.eatstreetService.setRestaurant()
  }

  getRestaurants() {
    this.eatstreetService.getRestaurant().subscribe((data) => {
      console.log(data['restaurants']);
      this.restaurants = data['restaurants'];
    })
  }

  onSelect(): void {
    this.setRestaurants()
  }

  ngOnInit() {
    this.setRestaurants()
    this.getRestaurants()
  }

}

RestaurantsList.component.ts

export class CardsComponent implements OnInit {
  restaurants;

  constructor(private eatstreetService: EatstreetService) { }

  getRestaurants() {
    this.eatstreetService.getRestaurant().subscribe((data) => {
      console.log(data['restaurants']);
      this.restaurants = data['restaurants'];
    })
  }
  setRestaurants() {
    this.eatstreetService.setRestaurant()
  }

  ngOnInit() {
    this.getRestaurants()
  }

I have researched similar issues, but none of the suggested solutions seem to work for me.

Answer №1

Ensure that you emit the value from your BehaviorSubject after receiving the http get response:

 @Injectable()
    export class FoodDeliveryService {

      radius;
      address;
      public restaurantList: = new ReplaySubject(1);

      constructor(private httpClient: HttpClient) { }

      public updateRestaurantList(){
        let params = new HttpParams();
        params = params.append('method', 'delivery');
        params = params.append('pickup-radius', this.radius);
        params = params.append('street-address', this.address);
        params = params.append('access-token', this.token)
        this.httpClient.get(`https://api.com/publicapi/v1/restaurant/search`, {params})
                     .subscribe(resp => this.restaurantList.next(resp));

      }

      public retrieveRestaurants(): Observable<any>{
        return this.restaurantList.asObservable();
      }
    }

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

Employing union types and type guards within templates while utilizing ngForOf in Angular

When utilizing array: (A | B)[] within an *ngFor, it appears that the only option is to use $any() extensively throughout the template. Is there a more efficient way to handle this situation? I've managed to bypass typing altogether by using $any(), ...

Discussing recursive types A <--> B with generics in TypeScript

I'm currently working with the following TypeScript code: type DormNodePredicate = DormEdge | (() => DormNode<DormNodePredicateRecord>); interface DormNodePredicateRecord { [key: string]: DormNodePredicate; } export class DormNode<DNPR ...

Prepending the emulated prefix to Angular 6-7 ViewEncapsulation

Can we customize the tags generated when using ViewEncapsulation.Emulated in an Angular 2-7 component? Currently, it generates tags like [_ngContent-C0], but is there a way to add a custom string to the generated tag, such as [_ngContent-C0-myApp]? Thank ...

Quill editor fails to trigger the (change) event when I modify the toolbar settings

I am facing an issue with capturing Quill editor events. The code snippet below shows how I am trying to capture the event, but when I change something using the toolbar, the event is not captured. Can someone please help me understand how to get this ev ...

The JSX component cannot be 'FieldArray' at this time

I'm working on a next.js project and using the Formik component. However, I encountered a type error that says "'FieldArray' cannot be used as a JSX component." Can anyone help me resolve this issue? Here is the error message: 'FieldAr ...

How can I retrieve the name of a constant enum member in TypeScript as a string?

Consider the following const enum declaration: const enum Snack { Apple = 0, Banana = 1, Orange = 2, Other = 3 } Is it possible in TypeScript to retrieve the string representation of a specific member? In C#, this could be achieved with ...

The issue in Angular2 viewmodel where the boolean value fails to update the *ngIf template

I'm seeking assistance with an unusual issue in my Angular2 and Typescript application. Within my template, I have the following HTML utilizing ngIf: <div *ngIf="loading" class="row"> <div class="small-3 small-centered columns" > ...

Unlock specific elements within the "sub-category" of a combined collection

If my union type is structured like this: type StateUpdate = { key: 'surname', value: string } | { key : 'age', value: number }; This setup is convenient because it allows me to determine the type of the value based on the key. Howev ...

Angular 16 routing not loading content

I configured the routes in Angular v16 and encountered a blank page issue with the login and register functionality. I suspect it has to do with routing, but after checking multiple times, I couldn't pinpoint the exact problem. Below are snippets of t ...

Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class /** * @element my-element */ export class MyElement extends HTMLElement { publicMethod() {} /** @private */ privateMethod() {} } customElements.define('my-element', MyElement) ...

Creating packages for multiple Typescript projects that rely on a shared local module

I am currently developing a series of VSTS extensions, with each extension being its own independent Node project complete with its own package.json file and node_modules folder. The structure of the folders is as follows: - MyExtension - package.json ...

Using TypeScript to assert the type of a single member in a union of tuples, while letting TypeScript infer the types of the other members

Currently, I am attempting to implement type assertion for the "error-first" pattern. Within my function, it returns tuples in the format of ['error', null] or [null, 'non-error']. The specific condition I want to check for is error = ...

How can one effectively import and save data from a CSV file into an array comprised of objects?

I am looking to read a CSV file and store it in a variable for future access, preferably as an array of objects. However, when trying the following code snippet: const csv = fs .createReadStream('data.csv') .pipe(csv.default({ separator: &ap ...

Issue with FullCalendar-v4 not displaying all-day events

I am facing an issue with my calendar where recurring events are displaying correctly, but single allDay events are not rendering, and I suspect it may be a field problem. I've attempted to set the event's start time as an iso date, but it doesn ...

The required dependencies for @angular/[email protected] and @angular/[email protected] have not been fulfilled

Details: npm version: 3.10.10 and nodejs version: 6.11.1 I am in the process of setting up a .NET project with an angular web API but am encountering unmet dependencies: "unmet peer dependency @angular/[email protected] and @angular/[email prote ...

Issue with const declaration in Typescript and Node.js - initializer is missing

Encountering a syntax error with the following line of code. Error message: SyntaxError: Missing initializer in const declaration const dataMap : Map<string, any> = new Map(); ...

Ways to RESOLVE implicit any for accessing array property

Check out the code snippet below: function getUsername(): string { return 'john_doe'; } function sampleFunction(): void { const data = {}; const username: string = getUsername(); const age: any = 30; data[username] = age; // ...

Is the spread operator in React failing to function as anticipated?

In my current project, I encountered an issue while trying to pass a GeolocationCoordinates object to a child component using the spread operator. Strangely, in the child props, it appears as an empty object: interface HUDState { geoCoords: Geolocation ...

Executing a method with parameters in ngOnInit in Angular - A simple guide

Is it feasible to trigger a parametrized method in ngOnInit within the same component? I currently have an onclick(p.key) function in the html file, defined in the corresponding typescript file. However, my aim is to invoke it during ngOnInit. Is this achi ...

Tips for triggering a click event on a DOM element using Angular 2

How can I automatically load a component upon loading? <app-main id="tasks" [(ngModel)]="tasks"></app-main> Here is the function call from JavaScript: public tasks; ngOnInit() { this.tasks.click(); } I have attempted using document.getE ...