[英]How to set a value from observable to a variable in Angular 2
我有一个UsernameService
,它返回一个包含json对象的observable。 在AnotherService
,我想从UsernameService
对象中注入一个值。
到目前为止,我已经可以从UsernameService订阅可观察的内容,并且可以在控制台中显示它。 我什至可以向下钻取并显示控制台中对象的值之一。 但是,我不明白如何将该值分配给我可以使用的变量。 相反,当我尝试将值分配给变量时,在控制台中得到:Subscriber {closed: false, _parent: null, _parents: null...etc
这是我在控制台中成功显示可观察值的示例:
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));
}
}
上面的代码在控制台中正确显示了我试图分配给变量myFinalValue
的AccountName
字段的值。 但是,我似乎无法弄清楚哪里出了问题。
当我尝试使用相同的技术来简单地获取值(而不是在控制台中登录)时,我得到了泛型:订阅者{closed: false, _parent: null, _parents: null
...等等,正如我之前提到的。
这是导致我的错误的代码示例:
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);
}
}
最终,我的目标是将username.data [0] .AccountName中的值分配给变量myFinalValue 。
在此先感谢您的帮助!
因为您的调用是异步的(回调仅在完成时才起作用,所以您不知道何时),所以您无法从异步调用中返回值,因此只需在调用完成时分配它即可。 您需要执行与在subscribe
方法中获得的subscribe
username
相关的逻辑。 您需要创建一个字段来保留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));
}
}
事实证明,由于可观察的对象是异步的,并且正如Suren所说的:“回调仅在完成时才起作用,而您不知道何时”,因此,我需要初始化正在组件ngOnInIt中订阅第一个服务的代码。 从那里,我需要将订阅值传递给组件中的方法,该组件实际上将服务作为参数调用订阅。
这是我的组件的组成部分(您可以看到this.username值作为getCharges(accountName)传递给getCharges()方法:
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);
})
}
然后,在具有getUsernameService.getUsername()服务/方法的服务文件中,我可以轻松地将包含所需值的参数分配给变量。
希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.