首页 > 解决方案 > 在订阅中获取请求,跨组件属性问题

问题描述

我试图实现的目标是根据使用 ActivatedRoute 接收的参数发出获取请求,并使用获取的数据更新类属性。我已经完成了这一步。我遇到的困难是将获取的数据获取到我正在工作的组件中。下面是 component.ts 文件。

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);
      }
    )
  }
}

这行代码: this.dataStorageService.fetchSpell(this.spell.url) 是发起 fetch 请求的地方。fetchSpell 方法如下。

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

截至目前,console.log 语句的结果是我试图进入我的 SpellDetailComponent 的数据。我计划在 SpellDetailComponent 中创建一个名为 spelldata 的属性并对其进行更新。当获取请求发生在我的 DataStorageComponent 中时,我该如何处理?

标签: angular

解决方案


您始终可以将 subscribe 方法移动到调用该方法的 SpellDetailComponent 中。还是我误解了什么?

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; 
                })
          }
        )

进而

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

推荐阅读