0

database: Firebase

A user is able to add a post which looks a bit like:

postKey
  content: 'Content of the post',
  date: 'Date of post',
  author: 'authorKey' (author key is a login)

I think I shouldn't store all user information inside author because user someday would change something in his profile. I store just user key inside author and I'd like to get that user while printing post data inside view.

(service) That's the way I'm getting all posts (works correctly)

  getPosts(): Promise<any> {
    return new Promise(
      (resolve) => {
        this.af.database.list('/posts')
          .subscribe(response => {
            if(response.length > 0) resolve(response);
          })
      }
    )
  }

(component) Here I just assaign all these posts to posts array to print it inside view.

  posts: any;

  constructor(private homepageService: HomepageService) {
    homepageService.getPosts().then(
      response => {
        this.posts = response.reverse();
      });
  }

(view) Except all post data which I can print very easily, I'd like to get a user by post.author to print author data such as photo, firstname, surname, etc.

<div *ngFor="let post of posts" class="post-body">
    {{post.content}}
    {{homepageService.getUser(post.author)?.email}}
</div>

In this way I'd like to get the user. Here is getUser function

  getUser(key): Promise<any> {
    return new Promise(
      (resolve) => {
        this.af.database.object('/users/' + key)
          .subscribe(response => {
            resolve(response);
          })
      }
    );
  }

I know that line is wrong {{homepageService.getUser(post.author)?.email}} that there is no then inside view but I have tried also using async pipe. Now I am at a standstill. How should I do that?

1 Answer 1

1
{{(homepageService.getUser(post.author) | async)?.email}}

or

{{(homepageService.getUser(post.author) | async).email}}

with

  getUser(key): Observable<any> {
    return this.af.database.object('/users/' + key);
  }
Sign up to request clarification or add additional context in comments.

2 Comments

In that case my page crashes. Posts are not displayed and I can't do anything, can't click. All is frozen. (no errors in console). As I read this is expected behavior, because each time the method is called, you're returning a new instance of the promise, which when resolved, triggers change detection, which retrieves a new promise, which triggers change detection....
What if you return the observable you get from the database call directly? (see my updated answer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.