0

I've been looking at responses on this topic, and I'm having a hard time handling the response from a http call to the prismic api. I can get a response from the api, however,I'm have a hell of a time extracting. I'm newer Angular and Prismic, but apparently I do have the understanding of JS http responses that I thought

I want to extract from the response an update put them in HTML so document.getElementByTag("div").innerHTML = {response.property};...

Thank you for any feedback!

Model

    export class Post {
    page: number
    results_per_page: number
    results_size: 2
    total_results_size: number
    total_pages: number
    next_page: number
    prev_page: number
    results: Result
    version: number
    license: string
  }

  export class Result{
 
       id: string ;
       uid: number ;
       url: number ;
       type: number ;
       href: number ;
       tags: [] ;
       first_publication_date: number ;
       last_publication_date: number ;
       slugs: [] ;
       linked_documents: number ;
       lang: number ;
       alternate_languages: [ ];
       data: {}


 }

View

    <div class="container">

    <ul class="nav nav-pills">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Active</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">{{nav_name}}</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link disabled">Disabled</a>
        </li>
      </ul>
</div>

<div class="container" *ngFor=" let post of posts">
  <div class="card" *ngFor=" let d in post.results"  >
    <div class="card-title">
  </div>
  <div class="card-body">
  </div>
    <div>{{ d | json}}</div>
    <div>{{post | json}}</div>
  </div>
</div>

Servivce

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Post } from './nav/post';

@Injectable({
  providedIn: 'root'
})
export class ConfigService {

  fakeUrl = 'https://jsonplaceholder.typicode.com/posts/1';
  fakeUrl_2 = 'https://jsonplaceholder.typicode.com/posts';
  prismic = "https://myPrismicRepo.cdn.prismic.io/api/v2/documents/search?ref=Y..."

  constructor(private http: HttpClient) {
  }

  getPosts(): Observable<any>{
    
  //  return this.http.get<{[key: string]: Post}>(this.prismic)
  return this.http.get(this.prismic)
}
}


**Component** 

    import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { TitleStrategy } from '@angular/router';
import { map, Observable } from 'rxjs';
import { ConfigService } from '../config.service';
import { Post, Result} from './post';


@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css'],
})
export class NavComponent implements OnInit {
  nav_name = 'myShop';
  posts: Post[]=[];
  myData: Result[] =[];
  loading: Boolean =false;
  errorMessage;
  token="my prismic token"
  query ="&q=%5B%5B%3Ad+%3D+at%28document.id%2C+%22Yt3JQhAAACIAKlc3%22%29+%5D%5D"
  
  fakeUrl = 'https://jsonplaceholder.typicode.com/posts/1';
  fakeUrl_2 = 'https://jsonplaceholder.typicode.com/posts';
  prismic ="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"


  constructor(private configService: ConfigService) {

  
  }
   getPosts(){
    const postArray :Post[] = [];
       this.configService.getPosts()
       .pipe(
      //    map((responseData) =>{
      //    for(const key in responseData){
      //      //check for other key properties
      //      if(responseData.hasOwnProperty(key)) {
      //      postArray.push({...responseData[key], id: key})
      //     }
      //    }
      //    return postArray;
      //  })
      map( (response: Post) =>
         
      response.results[1].filter((x: Result) => x.id === "Yt3JQhAAACIAKlc3" )
         
      )
       )
       .subscribe((response) => {
         console.log(response);
        //  this.posts = response ;

       }, (error)=> {
        this.errorMessage = error;
           console.log(this.errorMessage );
          
           
           this.loading = false;
       }
       );
   }


  
  ngOnInit(): void {
    this.getPosts();
  }
}
user2920627
  • 95
  • 15
  • I would recommend putting your code into a StackBlitz Environment where your code can be inspected in a working environment. People can fork it, fix it and repost the solution here for other to benefit. Here's the link for StackBlitz: https://stackblitz.com/?starters=frontend – OneClutteredMind Jul 25 '22 at 04:56
  • thank you , Please the stackblitz hrere – user2920627 Jul 25 '22 at 16:51
  • https://stackblitz.com/github/TicoGitHubII/myShop?file=src/app/nav/post.ts – user2920627 Jul 25 '22 at 16:51

1 Answers1

0

So it turns out this was easy -- so to speak. Probably the reason for not many responses. But for rusty and novice devs this will help. I just went to the most simple Angular Http request format using the Observeable type to hold the response and for there it just digging into the array response one step and at a time. Each time creating the model interface that I needed and passing the view and using the *ngFor directive to interate over the update response model .

 getPosts(): Observable<any>{
    
  return this.http.get(this.prismic)
 
}
}

  getPosts() {

this.configService
  .getPosts()
  .subscribe(
    (response) => {
      let data = response['results'];
      this.myData.push(...data);
      let header =  response['results'][0].data.header;
      this.myPSHeader.push({...header}).toString;

      console.log(response);
      console.log( this.myData )
      
    },
    (error) => {
      this.errorMessage = error;
      console.log(this.errorMessage);

      this.loading = false;
    }
  );

}

As for the prismic helper packages, after all the long toiling , I dug deep into prismic community and found a demo for Angular and Prismic.
So I hope this helps someone. Thanks Prismic team _ ! Prismic Community

user2920627
  • 95
  • 15