【问题标题】:Angular 12 http request : invalid URLAngular 12 http 请求:无效的 URL
【发布时间】:2023-03-27 08:55:01
【问题描述】:

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

错误消息:消息:无法在“XMLHttpRequest”上执行“打开”:无效的 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>

【问题讨论】:

  • 您没有将返回类型指定为用户数组,并且还指定“res”必须是单个对象。这可能是您的错误的根源。
  • @cklimowski 错误的返回类型如何导致 Invalid Url 错误?
  • @cklimowski 很奇怪,这是我在几个网站上找到的确切代码 positronx.io/make-http-requests-with-angular-httpclient-api
  • 只是一个建议,我在你的代码中认为是不正确的。如果您进行了这些更改但仍然遇到问题,请使用您问题中的更改更新您的代码。
  • 我的猜测是,您的网址中有一些无效字符。有些 Unicode 字符看起来与“普通”字符完全一样,但在 url 中是无效的。这可能是通过 c&p 来自其他地方的 url 来实现的。尝试完全删除 url(以及稍后添加的用户部分)并从头开始重新输入。不要 c&p,但要真正输入!

标签: angular asp.net-web-api mvvm httprequest


【解决方案1】:

这是一个有效的堆栈闪电战:似乎与您的打字有关,我不太确定。但是这段代码确实有效,它使用正确的类型并观察整个HttpResponse 而不仅仅是它的主体。这也将 User 实现为 interface 而不是类。除非您需要更多的功能而不仅仅是属性的类型强制,否则建议这样做。另请注意,要获取订阅中的 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>

【讨论】:

    猜你喜欢
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多