3

Sou novo no uso do AngularJs e decidi estudar me baseando em um projeto do trabalho.

Meu problema é o seguinte:

Estou montando um projeto base usando o AngularJs 2 para consumir dados do Wordpress (WP) atraves da API REST do WP.

Nessa API eu busco um post do WP (post personalizado chamado noticia) e preciso pegar a imagem destacada nesse post, só que o JSON não retorna a URL da imagem, ele retorna o link para o json com as informações de media (informações que contém os dados da imagem) e o identificador dessa media.

Seguindo o tutorial do AngularJS 2, eu criei um service para noticia para pegar os dados na API do WP (mais abaixo os códigos) e também um service para media. No detail de noticia eu consumo os dados gerados pelo service de noticia e exponho eles na view, mas para pegar a imagem que tenho que consumir os dados gerados pelo service de media, através do identificador que está no json de noticia, aí surge o meu problema.

A solução que imaginei foi a mais óbvia no meu ponto de vista, fazer um método no detail de noticia que mediante o identificador da media eu pegasse esses dados, isso funciona, mas ao fazer isso, chamando este método na view, ela entra em loop de requisição. Imaginei então fazer isso no próprio componente detail de noticia, mas lá o objeto noticia está indefinido, logo não tenho esse identificador para fazer a requisição.

Imagino que seja uma solução bem simples, mas não tenho nem ideia de como resolver, já fazem vários dias que estou travado nisso.

Qual seria a melhor solução?

Códigos

noticia.service.ts

import {Noticia} from "./noticia";
import {Injectable} from "@angular/core";
import {Http, Response, Headers, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Observable";
import {AppConstants} from ".././app-constants";
import "rxjs/Rx";

@Injectable()
export class NoticiaService {

    constructor(private _http: Http) { }

    private _apiUrl: string = AppConstants.API_URL;

    getNoticias() {
        return this._http.get(this._apiUrl + "noticias")
            .map(res => res.json())
            .catch(this.throwError);
    }

    getNoticia(id: number) {
        return this._http.get(this._apiUrl + "noticias/:id".replace(":id", id.toString()))
        .map(res => res.json())
        .catch(this.throwError);
    }

    private throwError(response) {
        return Observable.throw(response.json().error || "Server error")
    }

}

media.service.ts

import {Media} from "./media";
import {Injectable} from "@angular/core";
import {Http, Response, Headers, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Observable";
import {AppConstants} from ".././app-constants";
import "rxjs/Rx";

@Injectable()
export class MediaService {

    public medias: Array<Media>;
    constructor(private _http: Http) { }

    private _apiUrl: string = AppConstants.API_URL;

    getMedias() {
        return this._http.get(this._apiUrl + "media")
            .map(res => res.json())
            .catch(this.throwError);
    }

    getMedia(id: number) {
        return this._http.get(this._apiUrl + "media/:id".replace(":id", id.toString()))
                .map(res => res.json())
                .catch(this.throwError);
   }

    private throwError(response) {
       return Observable.throw(response.json().error || "Server     error")
    }

}

noticia-detail.component.ts

    import {Component, OnInit} from "@angular/core";
    import {NoticiaService} from "./noticia-service";
    import {MediaService} from "../medias/media-service";
    import {RouteParams} from '@angular/router-deprecated';

    import {Noticia} from "./noticia";
    import {Media} from "../medias/media";
    import {AppConstants} from ".././app-constants";



    @Component({
        templateUrl: "app/view/noticias/noticia-detail.html",
    })

    export class NoticiaDetailComponent implements OnInit {

        public noticia: Noticia;
        public imagemDestaque: Media;
        public constantes: AppConstants = AppConstants;

        constructor(private _routeParams: RouteParams, private _noticiaService: NoticiaService, private _mediaService: MediaService) { }

    ngOnInit() {
        let id = <number><any>this._routeParams.get("id");
        this._noticiaService.getNoticia(id).subscribe(data => this.noticia = data, error => console.log(error));
    }

    public getImagemDestaque(id: number) {
        this._mediaService.getMedia(id).subscribe(data => this.imagemDestaque = data, error => console.log(error));
    }

}

noticia-detail.html

<div *ngIf="noticia" class="col-md-12">
    <article>
        <section>
            <header>
                <h3>{{noticia.title.rendered}}</h3>
                <span class="text-muted">Publicado em {{constantes.formatarDataWP(noticia.modified)}}</span>
            </header>
            {{getImagemDestaque(noticia.featured_media)}}
                        <p *ngIf="imagemDestaque">
                            <img src="{{imagemDestaque.media_details.sizes.full.source_url}}" alt="{{imagemDestaque.title.rendered}}" title="{{imagemDestaque.title.rendered}}"/>
                        </p>
        </section>
    </article>
</div>

noticia.json

{
  "id": 116,
  "date": "2016-06-01T10:55:27",
  "date_gmt": "2016-06-01T13:55:27",
  "guid": {
    "rendered": "http://localhost/gerenciadorWP/?post_type=noticias&#038;p=116"
  },
  "modified": "2016-06-02T16:51:28",
  "modified_gmt": "2016-06-02T19:51:28",
  "slug": "mais-uma-noticia",
  "type": "noticias",
  "link": "http://localhost/gerenciadorWP/en/blog/noticias/mais-uma-noticia/",
  "title": {
    "rendered": "(Português do Brasil) Mais uma noticia"
  },
  "content": {
    "rendered": ""
  },
  "excerpt": {
    "rendered": ""
  },
  "featured_media": 127,
  "comment_status": "open",
  "ping_status": "closed",
  "tags": [],
  "acf": {
    "corpo": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
    "resumo": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut a",
    "chapeu": "Chapéu (ante-título)",
    "subtitulo": "Subtítulo",
    "origem": "",
    "autor": "Jeffersson",
    "documentos": [
      123
    ],
    "fotos": [
      105
    ]
  },
  "_links": {
    "self": [
      {
        "href": "http://localhost/gerenciadorWP/en/wp-json/wp/v2/noticias/116"
      }
    ],
    "collection": [
      {
        "href": "http://localhost/gerenciadorWP/en/wp-json/wp/v2/noticias"
      }
    ],
    "about": [
      {
        "href": "http://localhost/gerenciadorWP/en/wp-json/wp/v2/types/noticias"
      }
    ],
    "replies": [
      {
        "embeddable": true,
        "href": "http://localhost/gerenciadorWP/en/wp-json/wp/v2/comments?post=116"
      }
    ],
    "version-history": [
      {
        "href": "http://localhost/gerenciadorWP/en/wp-json/wp/v2/noticias/116/revisions"
      }
    ],
    "wp:featuredmedia": [
      {
        "embeddable": true,
        "href": "http://localhost/gerenciadorWP/en/wp-json/wp/v2/media/127"
      }
    ],
    "wp:attachment": [
      {
        "href": "http://localhost/gerenciadorWP/en/wp-json/wp/v2/media?parent=116"
      }
    ],
    "wp:term": [
      {
        "taxonomy": "post_tag",
        "embeddable": true,
        "href": "http://localhost/gerenciadorWP/en/wp-json/wp/v2/tags?post=116"
      }
    ],
    "curies": [
      {
        "name": "wp",
        "href": "https://api.w.org/{rel}",
        "templated": true
      }
    ]
  }
}

media.json

{
  "id": 127,
  "date": "2016-06-02T16:51:16",
  "date_gmt": "2016-06-02T19:51:16",
  "guid": {
    "rendered": "http://localhost/gerenciadorWP/wp-content/uploads/2016/06/2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it.jpeg"
  },
  "modified": "2016-06-02T16:51:16",
  "modified_gmt": "2016-06-02T19:51:16",
  "slug": "2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it",
  "type": "attachment",
  "link": "http://localhost/gerenciadorWP/en/blog/noticias/mais-uma-noticia/2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it/",
  "title": {
    "rendered": "2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it"
  },
  "author": 1,
  "comment_status": "open",
  "ping_status": "closed",
  "alt_text": "",
  "caption": "",
  "description": "",
  "media_type": "image",
  "mime_type": "image/jpeg",
  "media_details": {
    "width": 2560,
    "height": 1600,
    "file": "2016/06/2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it.jpeg",
    "sizes": {
      "thumbnail": {
        "file": "2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it-150x150.jpeg",
        "width": 150,
        "height": 150,
        "mime_type": "image/jpeg",
        "source_url": "http://localhost/gerenciadorWP/wp-content/uploads/2016/06/2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it-150x150.jpeg"
      },
      "medium": {
        "file": "2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it-300x188.jpeg",
        "width": 300,
        "height": 188,
        "mime_type": "image/jpeg",
        "source_url": "http://localhost/gerenciadorWP/wp-content/uploads/2016/06/2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it-300x188.jpeg"
      },
      "medium_large": {
        "file": "2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it-768x480.jpeg",
        "width": 768,
        "height": 480,
        "mime_type": "image/jpeg",
        "source_url": "http://localhost/gerenciadorWP/wp-content/uploads/2016/06/2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it-768x480.jpeg"
      },
      "large": {
        "file": "2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it-1024x640.jpeg",
        "width": 1024,
        "height": 640,
        "mime_type": "image/jpeg",
        "source_url": "http://localhost/gerenciadorWP/wp-content/uploads/2016/06/2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it-1024x640.jpeg"
      },
      "post-thumbnail": {
        "file": "2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it-1200x750.jpeg",
        "width": 1200,
        "height": 750,
        "mime_type": "image/jpeg",
        "source_url": "http://localhost/gerenciadorWP/wp-content/uploads/2016/06/2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it-1200x750.jpeg"
      },
      "full": {
        "file": "2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it.jpeg",
        "width": 2560,
        "height": 1600,
        "mime_type": "image/jpeg",
        "source_url": "http://localhost/gerenciadorWP/wp-content/uploads/2016/06/2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it.jpeg"
      }
    },
    "image_meta": {
      "aperture": "0",
      "credit": "",
      "camera": "",
      "caption": "",
      "created_timestamp": "0",
      "copyright": "",
      "focal_length": "0",
      "iso": "0",
      "shutter_speed": "0",
      "title": "",
      "orientation": "1",
      "keywords": []
    }
  },
  "post": 116,
  "source_url": "http://localhost/gerenciadorWP/wp-content/uploads/2016/06/2014_batman_arkham_knight-wide-batman-arkham-knight-has-shadow-of-mordor-s-combat-affected-it.jpeg",
  "_links": {
    "self": [
      {
        "href": "http://localhost/gerenciadorWP/en/wp-json/wp/v2/media/127"
      }
    ],
    "collection": [
      {
        "href": "http://localhost/gerenciadorWP/en/wp-json/wp/v2/media"
      }
    ],
    "about": [
      {
        "href": "http://localhost/gerenciadorWP/en/wp-json/wp/v2/types/attachment"
      }
    ],
    "author": [
      {
        "embeddable": true,
        "href": "http://localhost/gerenciadorWP/en/wp-json/wp/v2/users/1"
      }
    ],
    "replies": [
      {
        "embeddable": true,
        "href": "http://localhost/gerenciadorWP/en/wp-json/wp/v2/comments?post=127"
      }
    ]
  }
}

2 Respostas 2

1

Já usou algum método pra debugar ver quais valores estão chegando na variável imagemdestaque? Utilize o batarang pra debugar o js assim você já confere se o json está sendo corretamente carregado. Acredito que deve ser alguma coisa, provavelmente algum detalhe. Ou algum erro interno do angular, enfim sem debugar não tem jeito, em termos de código não vi nada errado.

Tenta executar direto pra ver se vai dar loop:

import {Component, OnInit} from "@angular/core";
    import {NoticiaService} from "./noticia-service";
    import {MediaService} from "../medias/media-service";
    import {RouteParams} from '@angular/router-deprecated';

    import {Noticia} from "./noticia";
    import {Media} from "../medias/media";
    import {AppConstants} from ".././app-constants";



    @Component({
        templateUrl: "app/view/noticias/noticia-detail.html",
    })

    export class NoticiaDetailComponent implements OnInit {

        public noticia: Noticia;
        public imagemDestaque: Media;
        public constantes: AppConstants = AppConstants;

        constructor(private _routeParams: RouteParams, private _noticiaService: NoticiaService, private _mediaService: MediaService) { }

 public getImagemDestaque(id: number) {
        this._mediaService.getMedia(id).subscribe(data => this.imagemDestaque = data, error => console.log(error));
    }

    ngOnInit() {
        let id = <number><any>this._routeParams.get("id");
        this._noticiaService.getNoticia(id).subscribe(data => this.noticia = data, error => console.log(error));

        this.getImagemDestaque(noticia.featured_media);
    }



}
3
  • Os valores chegam normal na variável imagemDestaque, mas o lance é que a view fica chamando em loop o metodo getImagemDestaque, isso que não estou entendendo. 16/06/2016 às 21:12
  • Eu não entendo muito de angular 2, mas já tentou executar direto pelo js , vou colocar na pergunta
    – luizluan
    17/06/2016 às 11:00
  • Não dá certo, pois no ngOnInit o objeto noticia não está definido ainda. 17/06/2016 às 13:16
1

Com ajuda do Nicolas Takashi, que me indicou estudar sobre LifeCycle Hooks no AngularJS 2 descobri o problema das múltiplas requisições. Assim consegui descobrir onde no LifeCycle do Componente o objeto noticia estava definido e lá eu fiz a chamada do service de media para pegar os dados da imagem. Após a imagem está definida eu cancelei a assinatura do service para não ter problemas com Memory Leak além de usar o hook de ngOnDestroy para liberar todos os services.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .