简体   繁体   English

如何在Angular 2+中将Observable内部的值作为函数返回

[英]How do I return the value inside of an Observable as the function in Angular 2+

Ok so basically I have been struggling to get user details stored in firebase using the user ID. 好的,基本上我一直在努力使用用户ID获取存储在Firebase中的用户详细信息。

I have a list of items that contain the user ID's in the object. 我有一个对象列表,其中包含用户ID。 I want this user id to be passed on to a function something like 我希望将此用户ID传递给类似的函数

<div *ngFor="let item of items">
    <p>{{getUsername(item.userId)}}</p>
</div>

in the html part of the app. 在应用程序的html部分中。

Then using this ID I want to pull username etc. which is stored in firebase as well and has the key as the same user id. 然后使用此ID,我想提取用户名等,该用户名也存储在firebase中,并且具有与相同用户ID相同的密钥。

Following options are the things I tried already; 我已经尝试过以下选项:

Option 1 (Just a function at the same component) 选项1(只是功能在同一组件上)

Outputs undefined which is I believe is because the function runs and returns the username variable before the subscription passes the data into it. 我认为这是输出未定义的原因,因为该函数运行并在订阅将数据传递到其中之前返回用户名变量。

constructor(public db: AngularFireDatabase){}

getUserName(id) {
    var username;
    this.db.object('users/' + id).valueChanges().subscribe(v => {
        username = v['username'];
    });
    return username;
}

Option 2 (created a service - Injectable so it passes it to object property) 选项2(创建了服务-可注入,因此将其传递给对象属性)

Outputs what I need but it shows the same for all the list elements 输出我需要的内容,但所有列表元素都显示相同的内容

username;

constructor(public db: AngularFireDatabase){}

getUserName(id) {
    this.db.object('users/' + id).valueChanges().subscribe(v => {
        this.username = v['username'];
    });
    return this.username;
}

So what I need is something like option 1 but it needs to return the value inside the observable once the observable got the data and passed it to the variable inside the function so it doesn't return an undefined value. 所以我需要的是类似于选项1的东西,但是一旦可观察对象获得数据并将其传递给函数内部的变量,它就需要在可观察对象内部返回值,这样它就不会返回未定义的值。

An important concept here is that the Observable is asynchronous, so you can't just "return" it's value as you might with a regular value. 这里的一个重要概念是Observable是异步的,因此您不能像常规值那样仅仅“返回”它的值。 You have to wait for it to emit a value before you can return that value. 您必须等待它emit一个值,然后才能返回该值。 Read more about that here: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754 . 在此处阅读有关此内容的更多信息: https : //gist.github.com/staltz/868e7e9bc2a7b8c1f754

For what you're trying to do specifically, I'd recommend just getting the Observable and using the 'async' pipe when you need it in the template. 对于您要尝试做的事情,我建议您仅获取Observable并在模板中需要时使用“异步”管道。

getUserData(id): Observable<YourData> {
  return this.db.object('users/' + id).valueChanges();
}

Then in your template, you can do something like this: 然后,您可以在模板中执行以下操作:

<li *ngFor=let user of users"> {{ getUserData(user.id) | async }}</li>

If you know the user id off the bat in your component and you want to get the user data for that user and use it in your component code, you can do something like this: 如果您知道组件中的用户id并想获取该用户的用户数据并在组件代码中使用它,则可以执行以下操作:

userData: YourData;
@Input() id: any; // provided by parent component

ngOnInit() { // OnInit lifecycle hook
  this.db.object('users/' + this.id).valueChanges().subscribe(data => this.userData = data);
}

But remember to handle the cleanup of the subscription. 但是请记住要处理订阅。

Try to do something like this: 尝试做这样的事情:

You can´t return the value for your subscribe, you have to do all inside the subscribe, if you have the main data you have to make a loop in your .ts calling your getUserName function and then create the final array with all the information, once you have your final array you can loop with *ngFor in your HTML. 您无法返回您的订阅的值,您必须在订阅中完成所有操作,如果您拥有主要数据,则必须在.ts中循环调用getUserName函数,然后使用所有信息创建最终数组,一旦有了最终数组,就可以在HTML中使用* ngFor循环。

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ModalController } from 'ionic-angular';


@IonicPage()
@Component({
  selector: 'page-restaurant-menu',
  templateUrl: 'restaurant-menu.html',
})


export class YourClass {
     public userName : String;
     public navData  : any;
     public final_array : any  

    constructor(public navCtrl: NavController, public navParams: NavParams, public) {
      this.navData = this.navParams.get('users');
      for(let user of this.navData){
          this.getUserName(user.id, user)
      }

  }


getUserName(id, user) {
    this.db.object('users/' + id).valueChanges().subscribe(v => {
        //here you have to create your final array whit the information
        this.final_array.push({user_data:user, user_name:v['username']})

    });
}


}

Then in your HTML you can use *ngFor 然后,您可以在HTML中使用* ngFor

<p>{{ final_array.user_name }}<p>

This is an idea how can you resolve this problem 这是一个想法,您如何解决此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Angular 中返回可观察对象内的值 - How to return a value inside an observable in Angular 如何从内部 function 向外部 function 返回一个值? - how do i return a value to an outside function, from the inside function? 如何在 Rxjs Angular 中订阅可观察对象 function 时处理错误并返回可观察对象 - How to handle error and return observable while subscribe inside an observable function in Rxjs Angular 如何在 Observable 订阅者角度 8 中返回承诺 - How to return a promise inside Observable subscriber angular 8 如何更改subscribe函数内的observable值? - How can i change value of observable inside of subscribe function? Angular:如何从一个可观察对象中获取另一个可观察对象的价值 - Angular: How to get value from an observable inside another observable Knockout.js - 如何在计算的observable中获取可观察属性的值? - Knockout.js - how do I get the value of an observable property inside a computed observable? 如何解析另一个Observable中的Observable? - rxjs - How do I resolve an Observable inside of another Observable? - rxjs 如何在角度中使用可观察和观察者? - How do I use observable and observer in angular? 如何从 angular 中的 Observable/http/async 调用返回响应? - How do I return the response from an Observable/http/async call in angular?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM