In Angular 8, a communication service facilitates interaction between parents and children

Using a Sharing service, I am able to pass data from my app component to the router-outlet render component. While I have been successful in passing strings and other data, I am now looking for a way to retrieve data from an API and share it with a component.

In the app component, there is a checkbox that allows users to select a category of books. When a new item is checked, the ChangeMessage method is called to send the Categoryid ID. This method then updates the list of books and shares it with another component for display:

@Injectable({providedIn:'root'})
export class DataService {
  private Messagesource = new Subject<any>();
  curentMessage$ = this.Messagesource.asObservable()
  constructor(private http: HttpClient, @Inject('BASE_URL') public url: string) { }
  ChangeMessage(message: any) {
    let result = this.http.get<Book[]>(this.url + 'api/Books');
    this.Messagesource.next(result);
  }
}

In the other component, the list of books is retrieved and updated as follows:

export class BookComponent implements OnInit {

  booklist: Book[]
  constructor(public service:CategoryServic,private ds:DataService) {}

    ngOnInit(): void {
      this.ds.curentMessage$.subscribe(x => this.booklist = x)
  }  
}

Answer №1

Identify the issue with the code snippet below

let output = this.http.get<Book[]>(this.url + 'api/Books');

It should be noted that the above code will result in an Observable, but your requirement is to pass a variable of type Book[], not an observable, to the next method's argument. Additionally, when using HttpClient, the get call will not execute unless you subscribe to the result. To gain a better understanding, let's refer to what Angular documentation states about HttpClient methods (check here):

An HttpClient method does not initiate the HTTP request until you invoke subscribe() on the observable returned by that method. This applies to all HttpClient methods.

In addition to that, I usually initialize the constructor of the Subject with a default value, which can help you grasp the concept better. For instance, if I have to track whether a user is logged in or not, I would initialize my subject as:

private isLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject(false); 

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

'The object of type '{}' does not support indexing with a 'string'

I am currently working on a React component that dynamically generates an HTML Table based on an array of objects. The columns to be displayed are specified through the property called tableColumns. While iterating through the items and trying to display ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

Initiating Angular APP_INITIALIZERThe Angular APP_INITIALIZER

I am a newcomer to Angular and currently utilizing Angular6 for development purposes. I have a specific query regarding my app. Before the app initializes, I need to invoke three services that provide configurations required by the app. Let's refer to ...

Having difficulties generating ngc and tsc AOT ES5 compatible code

I've explored various options before seeking help here. I have an angular2 library that has been AOT compiled using ngc. Currently, I am not using webpack and solely relying on plain npm scripts. Below is the tsconfig file being utilized: { "comp ...

Whenever I try to run npm start within my angular component, I encounter a compilation problem

I am currently working on dynamically rendering a component on one of my screens. To achieve this, I am utilizing the componentFactoryResolver.resolveComponentFactory and viewContainerRef.createComponent APIs. I have declared the variable "loadedComp : Glo ...

Displaying index.html exclusively using Angular Capacitor

I am currently working on converting my Angular application into an Android application using Capacitor. I have successfully installed Capacitor in my Angular project, which includes routing functionality. Here are the versions of the tools I am using: &qu ...

Integration of Mocha with WebStorm

WebStorm offers a useful feature that adds a small arrow next to describe() and it() keywords when writing tests with Mocha, allowing for easy manual execution. However, there is a challenge: I require additional setup before each test, leading me to use ...

Tips for showing JSON information in Nativescript

How can I display all values in a page using the provided JSON data? res { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "sensors": [ { "serial": "sensor1", "id": "1" }, ...

In order to iterate through a 'IterableIterator<number>', you must either enable the '--downlevelIteration' flag or set the '--target' to 'es2015' or newer

While attempting to enhance my Slider, I encountered an error when utilizing TypeScript React within this Next.js project: "Type 'IterableIterator' can only be iterated through when using the '--downlevelIteration' flag or with a ...

Typescript: object containing at least one property with the type T assigned

Is there a method to write the HasNumber interface in Typescript without receiving an error due to the fact that the HasNumberAndString interface includes a property that is not of type number? I am looking for a way to require the HasNumberAndString int ...

Issue with Angular 4: @HostBinding not properly rendering the CSS class on the host element, resulting in incorrect UI display

My creation of the ProductListComponent allows access to the child component, ProductRowComponent. Please see the code below: ProductListComponent import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { Product ...

Is it possible for the ionic ionViewDidEnter to differentiate between pop and setRoot operations?

I am facing an issue with my ionic 3 page where I need to refresh the data on the page only if it is entered via a navCtrl.setRoot() and not when returned to from a navCtrl.pop(). I have been using ionViewDidEnter() to identify when the page is entered, bu ...

Creating a PDF file with Angular 7: A step-by-step guide

I need to create a PDF report using data provided by the user and save it in an object. I've encountered methods that involve creating an HTML page, taking a screenshot, and then converting it to PDF. However, I'm seeking a solution to generate a ...

The FAB button animation is causing delays in the transition process and is not functioning as originally anticipated

I am facing an issue with the FAB button and 3 Icons. The functionality is working fine on click for both show and hide actions, but the transition is too delayed. I want the icons to appear step by step, even though I have adjusted the transition delay se ...

Raycaster in Three.js fails to recognize clicks on objects

Having trouble detecting clicks on Three.js objects using a raycaster in Angular? Here's the code I'm working with: @Component({ selector: 'app-viewer-3d', templateUrl: './viewer3d.component.html', styleUrls: ['./vi ...

Issue in kendo-angular-upload: Failure to trigger error event following a 500 Server Error Code

When developing the Front End, I utilize Angular 7 to attempt uploading an image using Kendo: <kendo-upload [saveUrl]="uploadSaveUrl" [removeUrl]="uploadRemoveUrl" [restrictions]="uploadRestrictions" [mul ...

Ensure that TypeScript compiled files are set to read-only mode

There is a suggestion on GitHub to implement a feature in tsc that would mark compiled files as readonly. However, it has been deemed not feasible and will not be pursued. As someone who tends to accidentally modify compiled files instead of the source fil ...

Basic cordova application that transfers data from one page to another using typescript

Currently, I am developing an Apache Cordova application using TypeScript. However, I am facing a challenge in passing information from one HTML page to another using TypeScript. I would appreciate it if someone could guide me on the steps needed for nav ...

The "tsc" command in Typescript seems to be acting up. I've exhausted all possible solutions but

Hello there, I find myself struggling to run Typescript throughout the day while utilizing Visual Studio Code. My usual method involves installing TS globally: $ npm install -g typescript But every time I try to use it, I encounter the same error: bas ...

Stop Angular (click) binding from occurring when the variable is considered 'undefined'

Currently, I am enhancing a custom Angular component by adding callbacks using the standard Angular method, like so: (click)="data.callback ? data.callback() : undefined" This approach works smoothly; when no callback is specified, Angular handl ...