Javascript 如何向函数返回值并通过变量访问它
我的服务中有一个方法,我希望根据获取的值返回true或false,并访问组件中的值 我的服务文件:Javascript 如何向函数返回值并通过变量访问它,javascript,angular,return,Javascript,Angular,Return,我的服务中有一个方法,我希望根据获取的值返回true或false,并访问组件中的值 我的服务文件: checkProfile (user) { let p = { username: user, key: '00' } this.postMethod(p).subscribe( d => { return d['code'] == '000' ? true : false; } ) } 我
checkProfile (user) {
let p = {
username: user,
key: '00'
}
this.postMethod(p).subscribe(
d => {
return d['code'] == '000' ? true : false;
}
)
}
我希望了解上述价值的我的组件:
let a = myService.checkProfile(this.user);
如何让方法返回true或false,以便可以通过变量
a
访问它。现在,a
是未定义的您可以将checkProfile转换为承诺,这样您就可以在其他函数调用中使用async/await
async checkProfile (user) {
let p = {
username: user,
key: '00'
}
const d = await this.postMethod(p).toPromise()
return d['code'] == '000' ? true : false;
}
您还需要将组件函数标记为异步。在我看来,这一切都要容易得多,因为你不必处理多个订阅并记住取消订阅。我认为你应该返回你的postMethod 像这样:
checkProfile (user) {
let p = {
username: user,
key: '00'
}
return this.postMethod(p).subscribe(
d => {
return d['code'] == '000' ? true : false;
}
)
}
checkProfile应返回一个可观察的,使用map将值转换为布尔值。在这里阅读更多关于它的信息
checkProfile(用户):可观察{
设p={
用户名:user,
键:“00”
}
返回这个.postMethod(p).pipe(map(d=>{
返回d['code']='000'?真:假
}))
}
在组件中
export class YourComponent{
check$:Observable<boolean> // if you want it to subscribe multiple times
constructor(private myService:MyService){
this.check$: Observable<boolean> = myService.checkProfile(this.user); // if
you want it to subscribe multiple times
}
// the other approach, if you only want to subscribe here
someMethod(){
this.myService.checkProfile(this.user).subscribe((check:boolean)=>{
let a =check // here you have the value in ts.
})
}
}
导出类组件{
如果希望订阅多次,请选中$:Observable//
构造函数(私有myService:myService){
this.check$:Observable=myService.checkProfile(this.user);//如果
你想让它订阅多次吗
}
//另一种方法,如果你只想在这里订阅
someMethod(){
this.myService.checkProfile(this.user).subscribe((check:boolean)=>{
让a=检查//这里有ts中的值。
})
}
}
它现在返回subscribe函数,而不是像预期的那样返回true
或false
,我不会将它变成承诺,但如果你这样做,只需使用.toPromise(),但如何使用等待
,因为我只能在一个联同步函数中使用它耶@chrispback这也是我的首选,但我只是想用尽可能少的代码修改来展示一些东西。将更新为tidier@emmanuel,如果您添加了您的组件代码,我可以对此进行评论,但如果不是,则是,只需使函数异步即可。谢谢。成功了。我在想,有一种更简单的方法可以通过使用return
关键字将值返回给方法
checkProfile(user):Observable<boolean> {
let p = {
username: user,
key: '00'
}
return this.postMethod(p).pipe(map(d=>{
return d['code'] == '000' ? true : false
}))
}
export class YourComponent{
check$:Observable<boolean> // if you want it to subscribe multiple times
constructor(private myService:MyService){
this.check$: Observable<boolean> = myService.checkProfile(this.user); // if
you want it to subscribe multiple times
}
// the other approach, if you only want to subscribe here
someMethod(){
this.myService.checkProfile(this.user).subscribe((check:boolean)=>{
let a =check // here you have the value in ts.
})
}
}