0

Ihave 2 api ( users and category ), and I have relationship between this api in category id, and I have user Promise.all. How can I video this data in html code?

My Code :

  • frist API ( name in posts ):
{
  "list": [
    {
      "id": 1,
      "title": "samsung",
      "body": "samsung is ......",
      "userId": "1"
    },
    {
      "id": 2,
      "title": "google",
      "body": "google is ......",
      "userId": "1"
    },
    {
      "id": 1,
      "title": "yahoo",
      "body": "yahoo is ......",
      "userId": "2"
    }
  ],
  "count": 3,
  "success": true
}
  • second API ( name in users):
{
  "list": [
    {
      "userId": 1,
      "username": "Michil"
    },
    {
      "userId": 2,
      "username": "Alix"
    },
    {
      "userId": 3,
      "username": "Jon"
    }
  ],
  "count": 3,
  "success": true
}
  • and I created 2 interfaces for this API like this:
import { PostsList } from "./PostsList "

export interface Posts{
    list: PostsList[]
    count: number
    success: boolean
}
export interface PostsList {
    id: number
    title: string
    body: string
    userId: string
}
import { UsersList} from "./UsersList"

export interface Users{
    list: List[]
    count: number
    success: boolean
}
export interface UsersList{
    userId: number
    username: string
}
  • and I have created a new interface which combines both PostsList and UsersList like this:
export interface TableView {
  post: PostsList;
  user: UsersList;
}
  • and I created a service to get data by id that I pass it from another page from the APIS URL like this :
id: any;

constructor(private userService: UserService, private router: ActivatedRoute){ }

ngOnInit(): void {
    this.id = this.router.snapshot.params['id'];
  }

getPost(id : number): Observable<Posts>{
    return this.http.get<Posts>(`https://api.api.com/post/list/&id=${id}`).pipe(
      tap(posts=> console.log(posts)),
    );
 }

getUsers(): Observable<Users>{
    return this.http.get<Users>(`https://api.api.com/users/list`).pipe(
      tap(users => console.log(users)),
    );
 }
  • and I called this service in my component.ts like this:
import { TableView } from 'src/app/interfaces/tableview ';
dataSource: <TableView>();
constructor(private myService: MyService){ }

ngOnInit(): void {
    // Promise for getting results of both API's
    let dataPromise: Array<Promise<any>> = [];
    // Convert observables and push to this promise
    dataPromise.push(this.myService.getPosts().toPromise());
    dataPromise.push(this.myService.getUsers().toPromise());

// Do data manipulation after we get results from both Promises
    Promise.all(dataPromise).then((responseList) => {
      // First item in responseList is from getPosts
      let posts: Posts = responseList[0];
      // Second item in responseList is from getUsers
      let users: Users = responseList[1];
      // Temporary array for storing data
      let data: Array<TableView> = [];

      posts.list.forEach((x) => {
        data.push({
          post: x,
          user: users.list.filter((y) => y.userId.toString() === x.userId)[0], // get the user for this userId
        });
      });
      this.dataSource = <TableView>(data);
    });
  }
  • and view this data in HTML code like this:
<ul>
  <li>ID: {{dataSource.post.id}}</li>
  <li>Title: {{dataSource.post.title}}</li>
  <li>Body: {{dataSource.post.body}}</li>
  <li>UserName: {{dataSource.user.username}}</li>
</ul>
  • But It's not working.

  • How can I resolve this problem?

Kareem
  • 47
  • 8

1 Answers1

0

You can use ForkJoin to achieve the same by doing the following:

@Component({
  selector: 'my-app',
  template: ` 
    <div *ngIf="data">
       <!-- have an *ngFor to iterate over the contents of your data object -->
       <!-- in the format you have structured it -->
    </div>
  `,
})
export class AppComponent  {
  data: any;

  constructor(http: HttpClient) {
    const users = this.http.get<any>(`https://api.api.com/users/list`);
    const posts = his.http.get<any>`https://api.api.com/post/list/&id=${id}`);

    forkJoin([users, posts])
      .subscribe(res => {
        //console.log to view the data
        console.log ('Users', res[0]);
        console.log ('Posts', res[1]);
        const users = res[0];
        const posts = res[1];
        this.data = {
          // build your data here in any format that you want
          // and access it in your html template
        }
      });
  }
}

Console.log and debug your data to see what you are getting and configure this according to your need.

CodeWarrior
  • 5,026
  • 6
  • 30
  • 46