angular - 在订阅中获取请求,跨组件属性问题
问题描述
我试图实现的目标是根据使用 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 中时,我该如何处理?
解决方案
您始终可以将 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);
}
推荐阅读
- typescript - 属性 'currentTime' 没有初始化器,也没有在构造函数中明确分配
- c++ - 每次 qt windows 获得焦点时调用函数
- amazon-web-services - AWS Lambda 返回“无法导入模块”
- javascript - 如何删除html文本输入中文本之间的双空格
- ios - IOS 推送通知计数
- c# - 减去转换为 int 的字符串,然后返回字符串:
- mongodb - mongo 聚合中的 $push 和 $group
- c# - 每隔几秒在两个函数的执行之间切换
- laravel - Laravel 错误密码重置链接
- highcharts - 如何将 Highmap 图表与 Angular 5 应用程序集成?