【问题标题】:accessing variable from service in one component to another component in Angular 7从一个组件中的服务访问变量到Angular 7中的另一个组件
【发布时间】: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


【解决方案1】:

例如,您必须在要在其中使用服务的组件的构造函数中声明您的服务。您有一个名为 TestService 的服务。你想在你的 TestComponent 中使用这个服务。为此,您必须在 TestComponent 中使用依赖注入,执行以下操作:

export class TestComponent implements OnInit {
 constructor(private testService: TestService) {}

 ngOnInit() {
  this.testService.testMethod();
 }
}

【讨论】:

  • 我已将构造函数用作我拥有 samplefunc 的组件的一部分,我刚刚用完整的组件更新了我的问题。我想在另一个组件中使用存储在数组对象“testgetinfos”中的值。
猜你喜欢
  • 1970-01-01
  • 2020-06-18
  • 2017-11-22
  • 2016-12-16
  • 1970-01-01
  • 1970-01-01
  • 2023-01-05
  • 2016-09-28
  • 2016-09-16
相关资源
最近更新 更多