我有一个UsernameService
返回一个包含json对象的observable。在AnotherService
中,我想从UsernameService
对象中注入一个值。
到目前为止,我能够从UsernameService订阅observable,我可以在控制台中显示它。我甚至可以向下钻取并在控制台中显示对象中的一个值。但是,我不明白如何将该值赋给我可以使用的变量。相反,当我尝试将值赋给变量时,在控制台中我得到:订阅者{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
字段的值。但是,我似乎无法弄清楚我哪里出错了。
当我尝试使用相同的技术来简单地获取值(而不是登录控制台)时,我得到了通用:订阅者{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。
在此先感谢您的帮助!
因为您的调用是异步的(回调仅在完成时才起作用,您不知道何时),您无法从异步调用返回值,因此您只需在调用完成时分配它。您需要执行与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));
}
}
事实证明,由于observable是异步的,并且Suren说“回调仅在完成时才起作用,你不知道什么时候”,我需要启动订阅我的组件ngOnInIt中的第一个服务的代码。从那里,我需要将subscribe值传递给实际调用订阅的组件中的方法,将服务作为参数。
这是我的组件的部分(您可以看到传递给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);
})
}
然后在具有getUsernameService.getUsername()服务/方法的服务文件中,我可以轻松地将包含我所需值的参数分配给变量。
希望有所帮助!