Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 将功能从组件传递到服务_Angular - Fatal编程技术网

Angular 将功能从组件传递到服务

Angular 将功能从组件传递到服务,angular,Angular,我试图从服务中访问数据,但只有在调用服务函数中的某个组件函数时才能访问数据。我能做些什么吗 我尝试在observable内部使用回调,但这不起作用。在服务内部导入组件然后调用函数是一种好的做法吗 service.ts: serviceFunc1(){ //I will get some data from here after subscribing this.serviceFunc2(); CompoFunc1(); // Not able to do //Calli

我试图从服务中访问数据,但只有在调用服务函数中的某个组件函数时才能访问数据。我能做些什么吗

我尝试在observable内部使用回调,但这不起作用。在服务内部导入组件然后调用函数是一种好的做法吗

service.ts:
 serviceFunc1(){
   //I will get some data from here after subscribing
   this.serviceFunc2();
   CompoFunc1(); // Not able to do
   //Calling CompoFunc1() to get items variable(please read entire you'll get it)
}
  serviceFunc2(){
    //I will use the data that came from serviceFunc1() inside api(loop)
    //After subscribing the data I will get some data, that data I will be storing in some variable(assume variable is items)
  }

Component.ts:
  CompoFunc1(){
     //Now I need to acces the variable items inside this component
     //So this.service.items;
     //But to get items I need to call CompoFunc1() inside serviceFunc1 after serviceFunc2()  
 }
 ngOnInit(){
  this.service.serviceFunc1();
}
如果有任何问题,请随时提问

我只想访问组件内部的变量项。

您的服务通常不应该调用组件。如果它需要来自组件的数据,请在
this.service.serviceFunc1(myData)
调用中将该数据从组件传递给服务

public getData(args: any){
    this.data = args;
}
如果需要在服务调用后在组件中执行某些操作,请在服务调用后添加代码

服务

在这里调用
http.get
,但不要订阅

  getProducts(): Observable<Product[]> {
    return this.http.get<Product[]>(this.productsUrl)
  }

这就是您要做的吗?

您不需要订阅组件中的任何内容

public getData(args: any){
    this.data = args;
}
在服务中,设置从组件获取数据的函数

public getData(args: any){
    this.data = args;
}
在组件中,向服务发送数据,如下所示:

this.service.getData(myDataFromComponent);
该服务现在将myDataFromComponent数据集存储为this.data

您提到了使用API,所以我假设返回了一个可观察对象

serviceFunc1(args: any) {
    //This is where you work your magic with the data
}

serviceFunc2(args: any) {
    //Code to process the secondary data here:
}
确保嵌套函数,以便在继续代码之前返回:

serviceFunc3() {
    this.serviceFunc1.pipe(
      switchMap( results => {
        this.finalAnswer = this.serviceFunc2(results);
        //Additional processing/handling of data;
      })
    );
}

可能的重复我仍然不明白我一点也不明白你在要求或试图做什么。我猜不管是什么,你都让事情变得比需要的复杂得多。我向您推荐您的问题,并添加一些实际的业务逻辑/推理,说明您试图实现的目标以及为什么不关注func1 func2等。实际上,我需要从serivces到component获取值。但我无法获取该值,因为该值未存储在其中。我需要以某种方式调用compoFunc1()在serviceFunc()2之后,这样我可以在值存储在数据中后访问数据。您能否构建一个简单的stackblitz,用比您问题中的代码多一点的代码演示您试图实现的目标?我无法共享??我们不需要你的申请。只是用比你上面发布的内容更具逻辑性的东西来展示你的问题。