【发布时间】:2019-09-11 21:11:24
【问题描述】:
我有一个变量 testgetinfos,它存储了一个从服务返回的对象数组,我想在另一个组件中使用这个变量,
下面是我从服务中存储对象数组的函数,这里当我在这个函数中打印 testgetinfos 变量的输出时,它符合预期
samplefunc(var1,var2) {
this.testgetInfoService.retrieveAllinfos(this.var1,this.var2).subscribe(
response => {
this.testgetinfos= response;
this.router.navigate(['sample'])
console.log(this.testgetinfos)
}
)
}
该功能是以下组件的一部分。
import { Component, OnInit } from '@angular/core';
import { TestgetInfoService } from '../service/data/test-info.service';
import { Router } from '@angular/router';
export class testinfo {
constructor(
public id: number,
public testvar1: string,
public testvar2: string,
public testvar3: string
){
}
}
@Component({
selector: 'app-test-info',
templateUrl: './test-info.component.html',
styleUrls: ['./test-info.component.css']
})
export class testInfoComponent implements OnInit {
var1=''
var2=''
public test : string []
public testinfos : testinfo[]
constructor(
private testInfoService:TestgetInfoService,
private router:Router
) { }
ngOnInit() {
}
samplefunc(var1,var2) {
this.testgetInfoService.retrieveAllinfos(this.var1,this.var2).subscribe(
response => {
this.testgetinfos= response;
this.router.navigate(['sample'])
console.log(this.testgetinfos)
}
)
}
}
下面是“示例”组件的脚本,我试图在其中打印 testgetinfos 变量的输出,
import { Component, OnInit } from '@angular/core';
import { Testinfo } from '../test-info/test-info.component';
@Component({
selector: 'app-sample',
templateUrl: './sample.component.html',
styleUrls: ['./sample.component.css']
})
export class sampleComponent implements OnInit {
constructor() { }
};
ngOnInit() {
this.displayinfo();
}
displayinfo(){
console.log("Gather info")
console.log(this.testinfos)
}
}
【问题讨论】:
-
samplefunc在哪里声明?在 sampleComponent 或 service 中? -
我很确定您也必须在第二个组件中使用 testgetInfoService.retrieveAllinfos()。这似乎是最简单的解决方案。但也许您的问题可以改进以澄清您是否尝试做一些不同的事情?
-
samplefunc 在单独的组件中声明。我正在使用基于此组件中提供的输入值的服务检索值。
-
@DillonFlohr 感谢您的通知,我错过了添加该组件,刚刚更新了我的问题
标签: angular