Angular 订阅内的获取请求,跨组件属性问题
我试图实现的目标是基于使用ActivatedRoute接收的参数发出获取请求,并使用获取的数据更新类属性。我已经迈出了这一步。我所面临的困难是将获取的数据获取到我正在使用的组件中。下面是component.ts文件Angular 订阅内的获取请求,跨组件属性问题,angular,Angular,我试图实现的目标是基于使用ActivatedRoute接收的参数发出获取请求,并使用获取的数据更新类属性。我已经迈出了这一步。我所面临的困难是将获取的数据获取到我正在使用的组件中。下面是component.ts文件 import { Component, OnInit} from '@angular/core'; import { Spell } from '../spell.model'; import { SpellService } from '../spell.service'; imp
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)是启动获取请求的地方。下面是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);
}
您始终可以将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);
}
非常感谢。如果问题解决了,请将答案标记为已接受谢谢!如果问题解决了,请将答案标记为已接受