typescript 如何在 Angular 2 中将值从 observable 设置为变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46804020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:58:45  来源:igfitidea点击:

How to set a value from observable to a variable in Angular 2

angulartypescriptangular2-observables

提问by Sol

I have a UsernameServicethat returns an observable which contains a json object. In AnotherService, I want to inject a value from the UsernameServiceobject.

我有一个UsernameService返回一个包含 json 对象的 observable。在 中AnotherService,我想从UsernameService对象中注入一个值。

So far, I am able to subscribe to the observable from UsernameService and I can show it in the console. I can even drill down and show one of the values from the object in the console. However, I don't understand how to assign that value to a variable that I can then use. Instead, when I try to assign the value to a variable, in the console I get: Subscriber {closed: false, _parent: null, _parents: null...etc

到目前为止,我可以从 UsernameService 订阅 observable 并且可以在控制台中显示它。我什至可以向下钻取并在控制台中显示来自对象的值之一。但是,我不明白如何将该值分配给我可以使用的变量。相反,当我尝试将值分配给变量时,在控制台中我得到:订阅者{closed: false, _parent: null, _parents: null...etc

Here's my example where I am successfully showing the observable value in the console:

这是我在控制台中成功显示可观察值的示例:

import { UsernameService } from './username.service';
import { Injectable, OnInit } from '@angular/core';
import 'rxjs/Rx';

@Injectable()
export class AnotherService {

    username: any[] = [];

    constructor(private getUsernameService: UsernameService) { }

    someMethod() {
        let myFinalValue = this.getUsernameService.getUsername()
        .subscribe(username => console.log(username.data[0].AccountName));
    }
}

The code above results in the console correctly showing the value of the AccountNamefield which I am trying to assign to the variable myFinalValue. However, I cannot seem to figure out where I am going wrong.

上面的代码导致控制台正确显示AccountName我试图分配给变量的字段的值myFinalValue。但是,我似乎无法弄清楚我哪里出错了。

When I try to use the same technique to simply get the value (instead of log in console), I get the generic: Subscriber {closed: false, _parent: null, _parents: null...etc as I mentioned before.

当我尝试使用相同的技术来简单地获取值(而不是登录控制台)时,我得到了通用:订阅者{closed: false, _parent: null, _parents: null...等,正如我之前提到的。

Here's an example of the code that results in my error:

这是导致我的错误的代码示例:

import { UsernameService } from './username.service';
import { Injectable, OnInit } from '@angular/core';
import 'rxjs/Rx';

@Injectable()
export class AnotherService {

    username: any[] = [];

    constructor(private getUsernameService: UsernameService) { }

    someMethod() {
        let myFinalValue = this.getUsernameService.getUsername()
        .subscribe(username => this.username = username.data[0].AccountName);
        console.log(myFinalValue);
    }
}

Ultimately, my goal is to just assign the value from username.data[0].AccountNameto the variable myFinalValue.

最终,我的目标是将username.data[0] .AccountName 中的值分配给变量myFinalValue

Thanks in advance for your help!

在此先感谢您的帮助!

采纳答案by Sol

It turns out that since the observable is asynchronous and as Suren said "callback will work only when it is finished, you don't know when", I needed to initiate the code that was subscribing to the first service in my component ngOnInIt. From there, I needed to pass the subscribe value to the method in the component that actually calls the subscribe form the service as a parameter.

事实证明,由于 observable 是异步的,并且正如 Suren 所说的“回调仅在它完成时才起作用,你不知道什么时候”,我需要启动订阅我组件 ngOnInIt 中第一个服务的代码。从那里,我需要将订阅值传递给组件中实际调用服务作为参数的订阅的方法。

Here's the piece form my component (you can see the this.username value passed to the getCharges() method as getCharges(accountName):

这是我的组件的一部分(您可以看到传递给 getCharges() 方法的 this.username 值作为 getCharges(accountName):

getCharges(accountName) {
  this.getChargesService.getCharges(accountName)
  .subscribe((charges) => {
      this.charges = charges.data;
      }, (error) => console.log(error) 
      )
  }


ngOnInit() {
this.getUsernameService.getUsername()
   .subscribe(username =>  { 
        this.username = username.data[0].AccountName;
        this.getCharges(this.username);
        })
   }

Then in the service file with the getUsernameService.getUsername() service/method, I was easily able to assign the parameter which contained my desired value to a variable.

然后在带有 getUsernameService.getUsername() 服务/方法的服务文件中,我可以轻松地将包含所需值的参数分配给一个变量。

Hope that helps!

希望有帮助!

回答by Suren Srapyan

Because your call is an asynchronous (callback will work only when it is finished, you don't know when), you can't return a value from the asynchronous call, so you need only to assign it when the call is finished. You need to do your logic which is related to the usernameyou get in the subscribemethod. You need to create a field to keep the value of the usernamefor the later use in the class.

因为你的调用是异步的(回调只有在完成时才会起作用,你不知道什么时候),你不能从异步调用中返回一个值,所以你只需要在调用完成时赋值。您需要执行与username您在subscribe方法中获得的逻辑相关的逻辑。您需要创建一个字段来保留 的值以username供以后在类中使用。

@Injectable()
export class AnotherService {

    username: any[] = [];
    myFinalValue: string;

    constructor(private getUsernameService: UsernameService) { }

    someMethod() {
        this.getUsernameService.getUsername()
        .subscribe(username => this.myFinalValue = username.data[0].AccountName));
    }
}