Home > Blockchain >  Unable to iterate through data got from http request in angular
Unable to iterate through data got from http request in angular

Time:10-05

movies.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of,tap } from 'rxjs';


@Injectable({
  providedIn: 'root'
})

export class MoviesService {
  strings$=["test", "test2", "test3"];
  private result: string[] = [];
  getMovies():string[]{
    
    this.httpClient.get<string[]>("https://api.themoviedb.org/3/search/movie?api_key=5e8f8ec6555c2183cafa97a83f2ddde5e&language=en-US&page=1&include_adult=false&query=interstellar").forEach(m=>{
 console.log(m)
    return this.strings$;
  }
  
  constructor(private httpClient: HttpClient){
    
  }
}

The data that i got through code-this.httpClient.get<string[]>("https://api.themoviedb.org/3/search/movie?api_key=5e8f8ec6555c2183cafa97a83f2ddde5e&language=en-US&page=1&include_adult=false&query=interstellar").forEach(m=>{ console.log(m) is-

 The data I got from api is-

{"page":1,"results":[{"adult":false,"backdrop_path":"/vgnoBSVzWAV9sNQUORaDGvDp7wx.jpg","genre_ids":[12,18,878],"id":157336,"original_language":"en","original_title":"Interstellar","overview":"The adventures of a group of explorers who make use of a newly discovered wormhole to surpass the limitations on human space travel and conquer the vast distances involved in an interstellar voyage.","popularity":190.016,"poster_path":"/gEU2QniE6E77NI6lCU6MxlNBvIx.jpg","release_date":"2014-11-05","title":"Interstellar","video":false,"vote_average":8.4,"vote_count":29464},{"adult":false,"backdrop_path":"/qpynYr3NPHkj1E7UKfd0OWJ2e2n.jpg","genre_ids":[99],"id":301959,"original_language":"en","original_title":"Interstellar: Nolan's Odyssey","overview":"A look behind the lens of Christopher Nolan's space epic.","popularity":11.677,"poster_path":"/wUmyEjrLqYpJYjVMD2YR7IffFeE.jpg","release_date":"2014-11-05","title":"Interstellar: Nolan's Odyssey","video":false,"vote_average":7.7,"vote_count":161},{"adult":false,"backdrop_path":"/wUZID3WzrzuIQmcIjXahZkV1ItI.jpg","genre_ids":[878],"id":398188,"original_language":"en","original_title":"Interstellar Wars","overview":"For Millennia the Aliien force has watched and waited, a brooding menace that has now at last decided to take over the Earth. Communications systems worldwide are sent into chaos by a strange atmospheric interference and this has turned into a global phenomenon. A massive spaceship headed towards Earth and smaller spaceships began to cover entire cities around the world. Suddenly, the wonder turns into horror as the spaceships destroy the cities with energy weapons. When the world counterattacks, the alien ships are invincible to military weapons.  The survivors have to use their wits to kill the aliens, or die.","popularity":7.361,"poster_path":"/4uWZ8cdrXMLiyLNgdmqQCIM6z40.jpg","release_date":"2016-06-09","title":"Interstellar Wars","video":false,"vote_average":3.7,"vote_count":10},{"adult":false,"backdrop_path":null,"genre_ids":[99],"id":529107,"original_language":"en","original_title":"Inside Interstellar","overview":"Cast and crew of Christopher Nolan's 'Interstellar' discuss project origins, the film's imagery, ambitions, incorporating IMAX footage, the human element within the film, arm shooting locations outside of Calgary, the set construction and design, working with real corn, mechanical characters, including backstory, design, the blend of practical and digital effects in bringing them to life, the differences in the characters, the human performances behind the characters, the creative process behind the film's music, Icelandic locations, vehicle interiors, the processes of simulating the absence of gravity, the crucial end-film visuals and influence and inspiration for future generations","popularity":5.914,"poster_path":"/vemBplPKQhVe5cRWL7kxtgp15Vq.jpg","release_date":"2015-03-31","title":"Inside Interstellar","video":false,"vote_average":6.6,"vote_count":8},{"adult":false,"backdrop_path":null,"genre_ids":[35],"id":287954,"original_language":"en","original_title":"Lolita from Interstellar Space","overview":"An undeniably beautiful alien is sent to Earth to study the complex mating rituals of human beings, which leads to the young interstellar traveler experiencing the passion that surrounds the centuries-old ritual of the species.","popularity":9.85,"poster_path":"/nhWlip1s5YzhRFKGlHABGJrBhZn.jpg","release_date":"2014-03-08","title":"Lolita from Interstellar Space","video":false,"vote_average":5.3,"vote_count":7},{"adult":false,"backdrop_path":"/zjZmXyugypJ8aDc2WdybuG9cmoh.jpg","genre_ids":[99],"id":336592,"original_language":"en","original_title":"The Science of Interstellar","overview":"Matthew McConaughey narrates a fascinating look at Christopher Nolan's sci-fi film Interstellar, including scientific foundations, the work of consulting Scientist Kip Thorne, basic film themes, the science behind the search for planets capable of hosting life, space-time and the theory of relativity, the science of wormholes and black holes, crafting the film's visuals based on real scientific observation, the birth of the universe, the Dust Bowl and the evolution of dust as a toxin, the likelihood of future dust storms, the prospects of escaping a dying or doomed planet, and the possibilities of colonizing Mars.","popularity":6.338,"poster_path":"/qUZiVjFBd67WKktIrjJ9H3tesyo.jpg","release_date":"2014-11-25","title":"The Science of Interstellar","video":false,"vote_average":7,"vote_count":21},{"adult":false,"backdrop_path":"/lQS9il7YqGjmmBefZY27uG5wbzT.jpg","genre_ids":[99],"id":660698,"original_language":"en","original_title":"Faster Than Light: the Dream of Interstellar Flight","overview":"“Faster Than Light” explores the longstanding quest to develop spacecraft with enough power and speed to reach the stars. The film asks: What will it take to reach a newly discovered planet circling our Sun’s nearest neighbor, Proxima Centauri? Based on real science and engineering, “Faster Than Light” takes audiences on a thrilling journey into the future, aboard laser-driven space sails, antimatter engines, and even warp drive – right out of science fiction. “Who can say how far, and how fast, our technology will one day take us?” said director Thomas Lucas.","popularity":12.689,"poster_path":"/mbgJxB70uMFK2H8DXHUj5lAMgXx.jpg","release_date":"2017-06-07","title":"Faster Than Light: the Dream of Interstellar Flight","video":false,"vote_average":6,"vote_count":2},{"adult":false,"backdrop_path":null,"genre_ids":[],"id":838389,"original_language":"en","original_title":"Interstellar: Desgornia's Cut","overview":"A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.","popularity":1.201,"poster_path":"/geOB25wA6VHSlANpJ1UMyuokjJl.jpg","release_date":"","title":"Interstellar: Desgornia's Cut","video":false,"vote_average":0,"vote_count":0},{"adult":false,"backdrop_path":null,"genre_ids":[28,14,878],"id":460616,"original_language":"en","original_title":"Interstellar Civil War: Shadows of the Empire","overview":"The Imperial Empire is attacked by an Alliance of rebels led by fanatical mystics. The ruler, Empress Nobu, the 8th generation of her family, wants to execute a bold plan to rescue a cyborg, Leah C6, trapped on the battle ravaged planet Endor. The Empress believes Leah C6 holds the secret to destroying the Alliance of Rebels before their insurgency can kill millions of citizens of the Empire. She recruits her heroic fleet commander, Lord General Luka Raan and asks him to gather a team from the Empire's elite soldiers, the Galactic Rangers. Raan assembles the team in the ruins of Endor which was attacked by depraved Rebels and outlaws led by, Kindo-Ker, a fanatical mystic in Dark Energy. The Galactic Rangers begin a desperate search to find and rescue Leah C6 before the Alliance Rebels can.","popularity":1.511,"poster_path":"/1lDY7ZpEKOl3OaIQURjRbmFPfT8.jpg","release_date":"2018-04-15","title":"Interstellar Civil War: Shadows of the Empire","video":false,"vote_average":4,"vote_count":1},{"adult":false,"backdrop_path":"/jiD3YVlYyOqcIgLXGn1W7r0rL7p.jpg","genre_ids":[16,878,10402,12],"id":11049,"original_language":"ja","original_title":"Interstella 5555: The 5tory of the 5ecret 5tar 5ystem","overview":"Four talented alien musicians are kidnapped by a record producer who disguises them as humans. Shep, a space pilot in love with bass player Stella, follows them to Earth. Reprogrammed to forget their real identities and renamed The Crescendolls, the group quickly becomes a huge success playing soulless corporate pop. At a concert, Shep manages to free all the musicians except Stella, and the band sets out to rediscover who they really are -- and to rescue Stella.","popularity":14.728,"poster_path":"/AsvPgdcSlHocAbMp3yGZXjPiKKF.jpg","release_date":"2003-05-28","title":"Interstella 5555: The 5tory of the 5ecret 5tar 5ystem","video":false,"vote_average":7.8,"vote_count":334},{"adult":false,"backdrop_path":null,"genre_ids":[12],"id":552531,"original_language":"en","original_title":"The Prom Goer's Interstellar Excursion","overview":"High schooler Bennett lands the prom date of his dreams, Sophie, just days before the dance. Not long after, he witnesses Sophie being abducted by aliens in the middle of the New Mexico desert.","popularity":0.6,"poster_path":null,"release_date":"","title":"The Prom Goer's Interstellar Excursion","video":false,"vote_average":0,"vote_count":0},{"adult":false,"backdrop_path":null,"genre_ids":[35,18],"id":716603,"original_language":"en","original_title":"Only Interstellar Pinball Lives Forever","overview":"A young boy (played by an actual re-purposed Sunday school puppet) loses all faith in religion and afterlife options after having to bury his umpteenth pet, and vows that someday, when he's an adult with money, he'll find a way to become an 'eternal molecule' through science. Then, twenty-two years later, the playing of a pinball game brings dredges up the memory of that vow. Utilizing the hallucinogenic properties of alcohol and cough syrup blends, he undertakes the design of a pinball machine so poignant and dignified that it will convince scientists to create a pinball that we can download our consciousness into and thereby become digitally immortal.","popularity":0.6,"poster_path":"/uLJMGZlrkmvAO9Ria9zrp8GUqjx.jpg","release_date":"2010-06-28","title":"Only Interstellar Pinball Lives Forever","video":false,"vote_average":0,"vote_count":0},{"adult":false,"backdrop_path":null,"genre_ids":[],"id":763179,"original_language":"en","original_title":"Cosmic Journey: The Voyager Interstellar Mission and Message","overview":"The farthest Voyager: \"Cosmic Journey,\" a documentary premiering on the A&E cable network, tells the saga of the farthest-flung space journey to date - the Voyager interstellar mission, which started out 25 years ago and sailed past Jupiter, Saturn, Uranus and Neptune in the 1980s.","popularity":0.6,"poster_path":null,"release_date":"2003-01-16","title":"Cosmic Journey: The Voyager Interstellar Mission and Message","video":false,"vote_average":0,"vote_count":0},{"adult":false,"backdrop_path":null,"genre_ids":[],"id":986255,"original_language":"en","original_title":"How to Colonize the Stars: The Challenge of Interstellar Flight","overview":"Leading physicists and engineers in the field of interstellar travel discuss some of the deep issues we face when considering the problem of sending spacecraft to other stars. Will mankind ever truly become a space fairing civilization? Space colonization is no longer the fodder of science fiction, it is becoming a reality. We'll need to learn how to grow food, manufacture and live off our planet.","popularity":0.6,"poster_path":"/ddYoMPJioxY7qQxt7JyUaLCWMjw.jpg","release_date":"2009-06-09","title":"How to Colonize the Stars: The Challenge of Interstellar Flight","video":false,"vote_average":0,"vote_count":0},{"adult":false,"backdrop_path":null,"genre_ids":[28],"id":649745,"original_language":"zh","original_title":"星际流浪","overview":"The film tells that the catastrophe era, the earth is a waste land, the survivors are divided into wanderers and civilians, they are attached to the rule of the interstellar armed groups, in which the rogues rely on the plundering of civilian materials as a livelihood, making civilians in this harsh It is difficult to survive in the environment. After a hundred years of black technology explosion, it will bring about a civilized renaissance. In the face of the deteriorating planet, mankind is determined to continue the race and is determined to interstellar immigration. The \"curvature engine\" developed by the Chinese researcher Hailei has become the key to the interstellar immigration, and is also the target of robbers and interstellar armed groups.","popularity":1.148,"poster_path":"/oUWDbde5bWu9syBZglWDIwB1SPm.jpg","release_date":"2019-08-02","title":"Interstellar Wandering","video":false,"vote_average":0,"vote_count":0},{"adult":false,"backdrop_path":"/yl9QqtS3tbLCL4e6lHM349joALK.jpg","genre_ids":[28,53,878],"id":47663,"original_language":"en","original_title":"Trancers 5: Sudden Deth","overview":"Jack Deth is back for one more round with the trancers. Jack must attempt to find his way home from the other-dimensional world of Orpheus, where magic works and the trancers were the ruling class (before Trancers IV, that is). Unfortunately, Jack's quest to find the mystical Tiamond in the Castle of Unrelenting Terror may be thwarted by the return of Caliban, king of the trancers who was thought dead.","popularity":3.629,"poster_path":"/t4to2HtWP1lT6TkvTwSUD7cQqIH.jpg","release_date":"1994-11-04","title":"Trancers 5: Sudden Deth","video":false,"vote_average":4.9,"vote_count":14},{"adult":false,"backdrop_path":null,"genre_ids":[],"id":772265,"original_language":"zh","original_title":"星际变种","overview":"After long years of searching, the unknown creature was finally captured by the crew of the Thunder and named \"Baal\". Under the lure of Baal, the young Jamie released it. \"Baal\" who escaped from the experimental tank killed all the crew and Jamie's parents, and the young Jamie escaped back to Earth in an escape capsule alone. Twenty years later, a variant of \"Baal\" appeared on the earth, and Jamie began the story of the journey to save mankind and self-redemption","popularity":0.6,"poster_path":"/mMidfcVVaESbYdF9Tzgejp3FvPR.jpg","release_date":"","title":"Variant","video":false,"vote_average":0,"vote_count":0},{"adult":false,"backdrop_path":null,"genre_ids":[878],"id":261443,"original_language":"en","original_title":"Angry Planet","overview":"A criminal sentenced to life on a prison planet reveals his true purpose: to extract revenge on the killers who murdered his family.","popularity":1.623,"poster_path":"/6Bv0rl9R5gaN8X58LOjUT4MWKR7.jpg","release_date":"2008-01-01","title":"Angry Planet","video":false,"vote_average":2.8,"vote_count":2},{"adult":false,"backdrop_path":"/aPXNyG6035Wz2DhtGAgf7PeGNsz.jpg","genre_ids":[878,28],"id":47662,"original_language":"en","original_title":"Trancers 4: Jack of Swords","overview":"Jack is now back in the future. He had since lost Lena, and finds out that he's lost his other wife Alice to none other than Harris. While heading out for another assignment, something goes awry with the TCL chamber. Jack finds himself in a whole new dimension. He also runs across a different version of trancers. These guys seem to be in control of this planet. Jack manages to assist a rebel group known as the \"Tunnel Rats\" crush the rule of the evil Lord Calaban.","popularity":2.637,"poster_path":"/ec081IWKkRalPO14KAmqJ2vWeYB.jpg","release_date":"1994-02-02","title":"Trancers 4: Jack of Swords","video":false,"vote_average":5.4,"vote_count":21},{"adult":false,"backdrop_path":"/ynF37QsffZ1b3Xm2ktpb79ioP6R.jpg","genre_ids":[99],"id":436305,"original_language":"en","original_title":"The Farthest","overview":"The captivating tales of the people and events behind one of humanity's greatest achievements in exploration: NASA's Voyager mission.","popularity":5.732,"poster_path":"/jHbSJo4FoKvqaGn3b7q49bcSYVZ.jpg","release_date":"2018-03-15","title":"The Farthest","video":false,"vote_average":7.7,"vote_count":42}],"total_pages":1,"total_results":20}

Now, I am unable to parse the above data, using m.results or other methods. Pls help

CodePudding user response:

export class MoviesService {
  strings$=["test", "test2", "test3"];
  private result: string[] = [];
  getMovies():string[]{
    
  
  constructor(private httpClient: HttpClient){
    this.httpClient
      .get<string[]>('your url')
      .subscribe(res => console.log(res));
  }
}

I would suggest your learn about typescript and RxJS a bit more before using Angular.

CodePudding user response:

If you want to treat this data in the service and want to subscribe from a component, you can use the RxJs methods to treat this data.

This code will get the API response, treat it and return an Observable to be subscribed in the component after you inject the service on it.

export class MoviesService {
  getMovies(): Observable<string[]>{
    return this.httpClient.get<string[]>(<url>).pipe(
        map((res) => 
            { // Do something with your data here }
        )
    )}
  
  constructor(private httpClient: HttpClient){}
}
  • Related