Angular: Как создать API для метода PUT? - PullRequest
0 голосов
/ 15 марта 2019

Здесь у меня есть бэкэнд API, который я создаю метод put, чтобы связать его с базой данных.Я сохраняю зарегистрированный сеанс, и оттуда я хочу создать метод put на основе пользователя, который вошел в систему.

login

$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;
       }));
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...