Advertisement
Guest User

Untitled

a guest
Jul 26th, 2017
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. import { Component } from '@angular/core';
  2. import {PostService} from './post.service';
  3.  
  4. @Component({
  5. selector: 'app-root',
  6. template: `
  7.  
  8. {{test}}
  9. <ul>
  10. <li *ngFor="let item of jsonArray">
  11. {{item.title}} a
  12. </li>
  13.  
  14. </ul>
  15. <button on-click="onClick()">button</button>
  16. `
  17.  
  18.  
  19. })
  20. export class AppComponent {
  21. test;
  22. jsonArray : any[];
  23. constructor(private _postService : PostService){
  24.  
  25.  
  26. }
  27.  
  28. onClick(){
  29. this.jsonArray = this._postService.getPosts();
  30. this.test = "clicked";
  31. }
  32.  
  33. ngOnInit(){
  34. this.jsonArray = this._postService.getPosts();
  35. this.test = "init";
  36.  
  37. }
  38.  
  39. }
  40.  
  41. import {Http} from '@angular/http'
  42. import 'rxjs/add/operator/map';
  43. import {Injectable} from '@angular/core';
  44.  
  45.  
  46. @Injectable()
  47. export class PostService {
  48.  
  49. private _url = "https://jsonplaceholder.typicode.com/posts";
  50.  
  51. jsonArray: any[];
  52. getPosts():any[]{
  53. //return this._http.get(this._url).map(res =>res.json());
  54. this._http.get(this._url).subscribe(response => {
  55. this.jsonArray = response.json();
  56. console.log(response.json());
  57. console.log("jsonArray",this.jsonArray);
  58. });
  59.  
  60. return this.jsonArray;
  61. }
  62.  
  63. createPost(post){
  64. return this._http.post(this._url,JSON.stringify(post)).map(res =>res.json());
  65. }
  66. constructor(private _http:Http ){
  67.  
  68. }
  69.  
  70.  
  71.  
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement