【问题标题】:Angular Service 404 not found when posting to JSON file发布到 JSON 文件时找不到 Angular Service 404
【发布时间】:2021-08-07 23:50:37
【问题描述】:

我有一个静态 json 文件,我正在尝试向其中添加新信息。用户可以在表单中输入详细信息,并在提交时将详细信息添加到 json。但是,即使 url 是正确的,每当我发出 POST 请求时,我都会收到 404。 json 文件位于 assets 文件夹中。错误截图:

rest-service.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { Login } from './login/Login';
import Ride from './book-ride-component/Ride';
import { Observable } from 'rxjs';

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

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

  private usersUrl = './assets/users.json';
  private ridesUrl = './assets/rides.json';

  constructor(private http: HttpClient) { }

  getUsers(): Observable<Login[]> { // method returns users data as a observable
    return this.http.get<Login[]>(this.usersUrl);
  }

  getRides(): Observable<Ride[]> { // method returns rides data as a observable
    return this.http.get<Ride[]>(this.ridesUrl);
  }

  addRide(newRide: Ride): Observable<Ride> { // method returns rides data as a observable
    return this.http.post<Ride>(this.ridesUrl, newRide);
  }

}

offer-ride-component.component.ts:

import { Component, OnInit } from '@angular/core';
import Ride from '../book-ride-component/Ride';
import { RestServiceService } from '../rest-service.service';

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

  constructor(private restServiceService: RestServiceService) { }

  ngOnInit(): void {
  }

  newRide : Ride = {
    id: 5,
    offerId : "",
    name : "",
    car : "",
    seatsLeft : 0,
    pickUp : "",
    destination : ""
  }
  success: boolean = false;
  errorMessage : string = ""

  addRide(newRide : Ride) {
    this.restServiceService.addRide(this.newRide).subscribe( //getBooks() method from bookService
      response => {
        this.success = true
        console.log("b")

        let ridesList : Ride[] = JSON.parse(sessionStorage.getItem("rides") || '{}');
        ridesList.push(newRide);
        sessionStorage.setItem("rides", JSON.stringify(ridesList));
      },
      error => {
        this.errorMessage = <any>error
        console.log(this.errorMessage)

      }
      );
  }

}

offer-ride-component.component.html:

<div class="container-fluid d-flex justify-content-center">
    <div class="card">
        <div class="card-header bg-primary text-light">
            Car Ride Registration Form
        </div>
        <div class="card-body">
            <form>
                <div class="form-group text-secondary mb-3">
                    <label for="username">Name</label>
                    <input [(ngModel)]="newRide.name" name="name" type="text" class="form-control" id="name">
                </div>
                <div class="form-group text-secondary mb-3">
                    <label for="startLocation">Start Location</label>
                    <input [(ngModel)]="newRide.pickUp" name="startLocation" type="text" class="form-control" id="startLocation">
                </div>
                <div class="form-group text-secondary mb-3">
                    <label for="destination">Destination</label>
                    <input [(ngModel)]="newRide.destination" name="destination" type="text" class="form-control" id="destination">
                </div>
                <div class="form-group text-secondary mb-3">
                    <label for="car">Car</label>
                    <input [(ngModel)]="newRide.car" name="car" type="text" class="form-control" id="car">
                </div>
                <div class="form-group text-secondary mb-3">
                    <label for="seats">Seats Available</label>
                    <input [(ngModel)]="newRide.seatsLeft" name="seats" type="number" class="form-control" id="seats">
                </div>
                
                <button (click)="addRide(newRide)" type="submit" class="btn btn-primary btn-block">Submit</button>
                <button class="btn btn-primary btn-block">Go Back</button>
                <p *ngIf="success" class="text-primary">Added Successfully!</p>
            </form>
        </div>
    </div>
</div>

rides.json:

[ 
    {
      "id" : 1,
      "offerId" : "1",
      "name" : "Thugget",
      "car" : "Toyota",
      "seatsLeft" : 3,
      "pickUp" : "Vanrose Junction",
      "destination" : "Gotham"
   },
   {
    "id" : 2,
    "offerId" : "2",
    "name" : "Thig",
    "car" : "Honda",
    "seatsLeft" : 2,
    "pickUp" : "PTP",
    "destination" : "Gotham"
   },
   {
    "id" : 3,
    "offerId" : "3",
    "name" : "Cracked",
    "car" : "Porshe",
    "seatsLeft" : 7,
    "pickUp" : "Gotham",
    "destination" : "East-Fort"
   },
   {
    "id" : 4,
    "offerId" : "4",
    "name" : "Mad",
    "car" : "Toyota",
    "seatsLeft" : 5,
    "pickUp" : "Gotham",
    "destination" : "Central Mall"
   } 
  ]

【问题讨论】:

    标签: json angular post components http-status-code-404


    【解决方案1】:

    注意:这是不可能的,也不符合逻辑,因为您想添加到系统中的文件中;你可以从JSON文件中读取。

    要向文件中添加内容,您需要打开、插入和关闭文件。

    使用 Database [mysql, sql, mongoDB, ...] 代替 Json 文件来帮助您执行GET,POST,@987654324 等操作@,PUT 并获得相应的经验。

    另外,当您调用 POST 方法 http 时,期望有一个 URL 可以帮助您在某处添加内容

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 2019-05-01
      • 2017-08-17
      • 2016-07-13
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      相关资源
      最近更新 更多