Fetch Request within a Subscription, Cross Component property issue

Viewed 19

The goal I am trying to achieve is to make a fetch request based off of params received using ActivatedRoute and to update a class property with the data fetched. I have achieved the first step of this. The struggle I am having is getting that fetched data to the component in which I am working in. Below is the component.ts file.

import { Component, OnInit} from '@angular/core';
import { Spell } from '../spell.model';
import { SpellService } from '../spell.service';
import { ActivatedRoute, Params } from '@angular/router';
import { DataStorageService } from 'src/app/shared/data-storage.service';

@Component({
  selector: 'app-spell-detail',
  templateUrl: './spell-detail.component.html',
  styleUrls: ['./spell-detail.component.css']
})
export class SpellDetailComponent implements OnInit {
  spell: Spell;
  id: number;

  constructor(private spellService: SpellService,
              private route: ActivatedRoute,
              private dataStorageService: DataStorageService) { }

  ngOnInit() {
    this.route.params
    .subscribe( 
      (params: Params) => {
        this.id = +params['id'];
        this.spell = this.spellService.getSpell(this.id);
        this.dataStorageService.fetchSpell(this.spell.url);
      }
    )
  }
}

The line of code: this.dataStorageService.fetchSpell(this.spell.url) is where the fetch request is initiated. The fetchSpell method is below.

fetchSpell(url) {
        return this.http
        .get('https://www.dnd5eapi.co' + url)
        .subscribe((res) => console.log(res))
    }

As of right now, the result of the console.log statement is the data in which I am trying to get into my SpellDetailComponent. I plan on creating a property called spelldata in the SpellDetailComponent and having that updated. How do I go about this as the fetch request occurs in my DataStorageComponent?

1 Answers

You can always move the subscribe method into SpellDetailComponent where you call the method. Or have I misunderstood something?

data: any

     ngOnInit() {
        this.route.params
        .subscribe( 
          (params: Params) => {
            this.id = +params['id'];
            this.spell = this.spellService.getSpell(this.id);
            this.dataStorageService.fetchSpell(this.spell.url).subscribe((res) => {
                console.log(res);
                this.data = res; 
                })
          }
        )

And then

fetchSpell(url) {
        return this.http
        .get('https://www.dnd5eapi.co' + url);
    }
Related