Angular:如何为方法PUT创建API?

时间:2019-03-15 13:29:25

标签: angular typescript angular7

在这里,我有一个后端API,我创建了一个put方法将其与数据库连接。我将一个已登录的会话存储在一个会话中,然后从那里我要根据已登录的用户创建put方法。

登录

$app->post('/login', function ($request, $response) {

  $input = $request->getParsedBody();
  $sql = "SELECT id, password FROM users WHERE id= :id";
  $sth = $this->db->prepare($sql);
  $sth->bindParam("id", $input['id']);
  $sth->execute();
  $user = $sth->fetchObject();

  if(!$user) {
     return $this->response->withJson(['error' => true, 'message' => 'NO ID '], 404)->withHeader('Content-type', 'application/json;charset=utf-8', 404);
  }
  // Compare the input password and the password from database for a validation
  if (strcmp($input['password'],$user->password)) {
      return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.'], 404)->withHeader('Content-type', 'application/json;charset=utf-8', 404);  
  }

  if (session_status() === PHP_SESSION_NONE) {
      session_destroy();
  }

  $_SESSION['user_id'] = $input['id'];

  return $this->response->withJson($input)->withStatus(200)->withHeader('Content-type', 'application/json;charset=utf-8', 200);
});

地址

$app->put('/address/[{id}]', function ($request, $response) {
  if (session_status() === PHP_SESSION_NONE) {
      session_start();
  }

  if(empty($_SESSION['user_id'])) {
      return $response->withJson(['error' => true, 'message' => 'Login please'], 403);
  }

  $input = $request->getParsedBody();
  $sql = "UPDATE address SET id =:id, s_pNumber =:s_pNumber, s_address =:s_address, s_pCode =:s_pCode, s_city =:s_city, s_state =:s_state, s_country =:s_country";
  $sth = $this->db->prepare($sql);
  $sth->bindParam("id", $input['id']);
  $sth->bindParam("s_pNumber", $input['s_pNumber']);
  $sth->bindParam("s_address", $input['s_address']);
  $sth->bindParam("s_pCode", $input['s_pCode']);
  $sth->bindParam("s_city", $input['s_city']);
  $sth->bindParam("s_state", $input['s_state']);
  $sth->bindParam("s_country", $input['s_country']);
  $sth->execute();

  return $response->withJson($input)->withStatus(200)->withHeader('Content-type', 'application/json;charset=utf-8', 200);
});

有人知道如何创建一个服务使其与后端连接吗?这是我在服务中已经编写的代码。

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';
import { Observable } from 'rxjs';

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

  // Base api url
  public url = 'http://localhost:8080';
  headerProperty: string;

  constructor(private http: HttpClient) { }

  loginstudent(data) {

    const postHttpOptions = {
      headers: new HttpHeaders({'Content-Type':  'application/json'})
    };

    postHttpOptions['observe'] = 'response';

    return this.http.post('http://localhost:8080/' + 'login', data, postHttpOptions)
       .pipe(map(response => {
         return response;
       }));
  }
}

0 个答案:

没有答案