Search code examples
angularangular-servicesangular-httpclient

Share specific value from a Service with different component in Angular


I am new in Angular and have a problem. I am trying to pass some data between components. I already tried different solutions found on the internet and I am not getting it right.

I get data with two values (headline and id) via an service from an api in one component (this works fine). While clicking on the headline, I want to be redirected to an another component and receive the id of the clicked headline in order to call another api endpoint. How do I call the specific value id and bring it into the other component?

This is my first service (working):

export class HeadlinesService {
   apiUrl = '...'

   httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json' })
   };

   constructor(private _http: HttpClient) { }

   getHeadlines(): Observable<Headline[]> {     
     return this._http.get<Headline[]>(this.apiUrl); 
   }

}

My headline class:

export class Headline {
   heading: string;
   id: string;
   source: string;
}

Here I call the Service in order to display the headlines (working)

export class NewArticleComponent implements OnInit {

    headlines$: Headline[];

    constructor(private headlineService: HeadlinesService, private deleteService: DeleteService, private router: Router) { }

    ngOnInit() {
       return this.headlineService.getHeadlines()         
       .subscribe(headline => this.headlines$ = headline)
    }
}

I need a service which receives the id from the service above (but only id) and calls another api endpoint with it.

apiURL = '.../{id}'

The calling of the data from this should work like the working service above, so my only problem is to pass the id from one serve to another.

I hope someone can help me :)


Solution

  • You can pass data on navigation with this:

    constructor(...
      router: Router,
      ...) {}
    
    goToPage(headerId) {
      this.router.navigate(['/header'], { queryParams: { headerId } });
    }
    

    Assuming you are doing it programatically (from inside your component.ts code)

    And on the "receiving" headers component

    sub: Subscription;
    headerId;
    
    constructor(
      private route: ActivatedRoute,
      private router: Router) {}
    
      ngOnInit() {
        this.sub = this.route
          .queryParams
          .pipe(flatMap(params => {
            this.headerId = params['headerId'];
            return this.apiService.getById(this.headerId);
          })).subscribe(
            response => {
              //You should have your header response from API here
            }
          );
      }