typescript Angular HTTP Rest API GET,POST,PUT,DELETE

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript Angular HTTP Rest API GET,POST,PUT,DELETE相关的知识,希望对你有一定的参考价值。

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class PostService {

  constructor(private http:HttpClient) { }

  getPosts() {
    return this.http.get('http://restapi.jomphp.com/wp-json/wp/v2/posts');
  }

  createPost(data) {

    //set authorization headers

    const token = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9yZXN0YXBpLmpvbXBocC5jb20iLCJpYXQiOjE1Mjk4MTQzMTMsIm5iZiI6MTUyOTgxNDMxMywiZXhwIjoxNTMwNDE5MTEzLCJkYXRhIjp7InVzZXIiOnsiaWQiOiIxIn19fQ.6cKDCcoP7pdUajTiEdWqhQmkwRat8zBQe3bfBK2gNqk';

    const headers = new HttpHeaders()
      .set('Authorization', token);

    return this.http.post('http://restapi.jomphp.com/wp-json/wp/v2/posts', data, { headers });
  }

  deletePost(id) {

    //set authorization headers

    const token = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9yZXN0YXBpLmpvbXBocC5jb20iLCJpYXQiOjE1Mjk4MTQzMTMsIm5iZiI6MTUyOTgxNDMxMywiZXhwIjoxNTMwNDE5MTEzLCJkYXRhIjp7InVzZXIiOnsiaWQiOiIxIn19fQ.6cKDCcoP7pdUajTiEdWqhQmkwRat8zBQe3bfBK2gNqk';

    const headers = new HttpHeaders()
      .set('Authorization', token);

    return this.http.delete('http://restapi.jomphp.com/wp-json/wp/v2/posts/' + id, { headers });
  }

}
import { PostService } from './../post.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-post',
  templateUrl: './post.component.html',
  styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {

  posts: any;

  constructor(private postService:PostService) { }

  ngOnInit() {
    this.getPosts();
  }

  getPosts() {

    this.postService.getPosts().subscribe(
      data => {
      
        this.posts = data;

        console.log(this.posts);
      }
    );

  }
  
  createPost() {

    //set to publish
    this.formData.status = 'publish';

    console.log(this.formData);

    this.postService.createPost(this.formData).subscribe(
      data => {
        console.log(data);

        //redirect to post list

        this.router.navigate(['post']);
      },
      error => {

      }
    );

  }

  deletePost(id) {

    let choice = confirm('Are you sure to delete?');

    if (choice) {

      console.log(id);

      this.postService.deletePost(id).subscribe(
        data => {
          this.getPosts();
        }
      );

    }

  }

}

以上是关于typescript Angular HTTP Rest API GET,POST,PUT,DELETE的主要内容,如果未能解决你的问题,请参考以下文章

Typescript,Angular 2 - 将 Json 解析为 http 中的对象

如何将 Angular $http 与 typescript 泛型一起使用

Angular2 + typescript + jspm:没有 Http 提供者( App -> Provider -> Http )

带有 TypeScript 错误的 Angular HTTP GET http.get(...).map 不是 [null] 中的函数

TypeScript - 我无法使用 Angular 2 使用 http get 调用我的 json

Typescript (Angular) - JSON 模型反序列化