Angular 12 个 http 请求:无效 URL

Angular 12 http request : invalid URL

我想在 https://jsonplaceholder.typicode.com/users 上提出请求,但我收到无效 URL 错误,但 URL 对我来说没问题。我真的不明白为什么。

错误消息:消息:无法在 'XMLHttpRequest' 上执行 'open':无效 URL

export class User {
    id: string;
    name: string;
    email: string;
    username: number;
}

import { User } from '../models/user';

@Injectable({
  providedIn: 'root'
})

export class UserService {

  // REST API
  endpoint = 'https://jsonplaceholder.typicode.com/';

  constructor(private httpClient: HttpClient) { }

  getUsers(): Observable<User> {
    return this.httpClient.get<User>(this.endpoint + 'users')
    .pipe(
      retry(1),
      catchError(this.processError)
    )
  }

  processError(err) {
    let message = '';
    if(err.error instanceof ErrorEvent) {
     message = err.error.message;
    } else {
     message = `Error Code: ${err.status}\nMessage: ${err.message}`;
    }
    console.log(message);
    return throwError(message);
 }
}

在组件中:

export class UserListComponent implements OnInit {

  Users: any = [];

  constructor(private crudService: UserService) {}
  ngOnInit() {
    this.fetchUsers();
  }

  fetchUsers() {
    return this.crudService.getUsers().subscribe((res: {}) => {
      this.Users = res;
    })
  }

}

在html

    <table class="table">
      <thead>
        <tr class="table-primary">
          <th>#User Id</th>
          <th>Name</th>
          <th>Us
er Name</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let data of Users">
          <th scope="row">{{data.id}}</th>
          <td>{{data.name}}</td>
          <td>{{data.username}}</td>
          <td>{{data.email}}</td>
        </tr>
      </tbody>
    </table>

这是一个有效的 stackblitz:似乎与您的打字有关,我不太确定。但是这段代码确实有效,它使用正确的类型并观察整个 HttpResponse 而不仅仅是它的主体。这也将 User 实现为 interface 而不是 class。建议这样做,除非您需要的功能不仅仅是属性的类型强制。另请注意,要获取订阅中的 Json 数据,它位于 res.body 中。这也正确地实现了订阅的 OnDestroyunsubscribe,如果您不使用 async pipe.

,这始终是一个好习惯

https://stackblitz.com/edit/angular-ivy-ue5zf4

组件文件:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject } from "rxjs";
import { takeUntil } from "rxjs/operators";
import { UserService } from './user-service';
import { User } from './user-interface'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent implements OnInit, OnDestroy {
  private unsubscribe$ = new Subject<void>();
  users: User[] = [];

  constructor(private userService: UserService){}

  ngOnInit(): void {
    this.userService.getUsers().pipe(takeUntil(this.unsubscribe$)).subscribe((res) => {
      this.users = res.body;
    });
  }

  ngOnDestroy(): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }
}

服务:

import { Injectable } from "@angular/core";
import {
  HttpClient,
  HttpResponse,
} from "@angular/common/http";
import { Observable, of, throwError } from "rxjs";
import { catchError, retry, tap } from "rxjs/operators";
// Interface for user
import { User } from './user-interface';

@Injectable({
  providedIn: 'root'
})

export class UserService {

  // REST API
  endpoint = 'https://jsonplaceholder.typicode.com/';
  usersApi = "users";

  constructor(private http: HttpClient) { }

  getUsers(): Observable<HttpResponse<User[]>> {
    return this.http.get<User[]>(this.endpoint + this.usersApi, { observe: "response"})
    .pipe(
      retry(1),
      catchError(this.processError)
    )
  }

  processError(err) {
    let message = '';
    if(err.error instanceof ErrorEvent) {
     message = err.error.message;
    } else {
     message = `Error Code: ${err.status}\nMessage: ${err.message}`;
    }
    console.log(message);
    return throwError(message);
 }
}

用户界面:

export interface User {
  id: string;
  name: string;
  email: string;
  username: number;
}

应用程序模块:

import { NgModule } from '@angular/core';
import { CommonModule } from "@angular/common";
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from "@angular/common/http";
import { AppComponent } from './app.component';
    
@NgModule({
  imports:      [ BrowserModule, CommonModule, FormsModule, HttpClientModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

HTML:

<table class="table">
  <thead>
    <tr class="table-primary">
      <th>#User Id</th>
      <th>Name</th>
      <th>User Name</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let data of users">
      <th scope="row">{{data.id}}</th>
      <td>{{data.name}}</td>
      <td>{{data.username}}</td>
      <td>{{data.email}}</td>
    </tr>
  </tbody>
</table>