我有一个UsernameService
返回包含json对象的observable的对象。在中AnotherService
,我想从UsernameService
对象中注入一个值。
到目前为止,我已经可以从UsernameService订阅可观察的内容,并且可以在控制台中显示它。我什至可以向下钻取并显示控制台中对象的值之一。但是,我不明白如何将该值分配给我可以使用的变量。相反,当我尝试将值分配给变量时,在控制台中,我得到:订阅服务器{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));
}
}
上面的代码将在控制台中正确显示AccountName
我尝试分配给变量的字段的值myFinalValue
。但是,我似乎无法弄清楚哪里出了问题。
当我尝试使用相同的技术来简单地获取值(而不是在控制台中登录)时,我得到了通用名称: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 => this.username = username.data[0].AccountName);
console.log(myFinalValue);
}
}
最终,我的目标是将username.data [0] .AccountName中的值分配给变量myFinalValue。
在此先感谢您的帮助!
事实证明,由于可观察的对象是异步的,并且正如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()服务/方法的服务文件中,我可以轻松地将包含所需值的参数分配给变量。
希望有帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句