作者:手机用户2502900545 | 来源:互联网 | 2022-12-26 13:07
我试图从API获取用户列表,但我收到以下错误:
TypeError: Cannot read property 'toLowerCase' of undefined
at HttpXsrfInterceptor.intercept (http.js:2482)
at HttpInterceptorHandler.handle (http.js:1796)
at HttpInterceptingHandler.handle (http.js:2547)
at MergeMapSubscriber.eval [as project] (http.js:1466)
at MergeMapSubscriber._tryNext (mergeMap.js:128)
at MergeMapSubscriber._next (mergeMap.js:118)
at MergeMapSubscriber.Subscriber.next (Subscriber.js:92)
at ScalarObservable._subscribe (ScalarObservable.js:51)
at ScalarObservable.Observable._trySubscribe (Observable.js:172)
at ScalarObservable.Observable.subscribe (Observable.js:160)
我有一个调用homeService.getUsers()的登录组件,它使用HttpClient来检索用户,但http请求永远不会到达服务器.
login.component.ts:
import { Component, OnInit } from '@angular/core';
import { HomeService } from '../service/home.service';
import { User } from '../domain/user';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
user: User = {
id: undefined,
userName: undefined,
password: undefined
};
users: User[];
constructor(
private homeService: HomeService
) { }
ngOnInit() {
this.getUsers();
}
getUsers(): void {
this.homeService.getUsers()
.subscribe(users => this.users = users);
}
}
Home.service:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
import { User } from '../domain/user';
import { MessageService } from '../service/message.service';
const httpOptiOns= {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class HomeService {
private usersUrl: 'http://localhost:8080/users';
constructor(
private http: HttpClient,
private messageService: MessageService
) { }
getUsers (): Observable {
return this.http.get(this.usersUrl)
.pipe(
tap(users => this.log(`fetched users`)),
catchError(this.handleError('getUsers', []))
);
}
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError (operation = 'operation', result?: T) {
return (error: any): Observable => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
private log(message: string) {
this.messageService.add(message);
}
}
和app.module:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { HttpClientXsrfModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { HomeService } from './service/home.service';
import { MessagesComponent } from './messages/messages.component';
import { MessageService } from './service/message.service';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
RegisterComponent,
MessagesComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
HttpClientXsrfModule.withOptions({
COOKIEName: 'My-Xsrf-COOKIE',
headerName: 'My-Xsrf-Header',
})
],
providers: [HomeService, MessageService],
bootstrap: [AppComponent]
})
export class AppModule { }
我可以看到日志记录中显示的错误消息,所以它似乎是来自HttpClient的错误.但在将Http请求发送到服务器之前,我无法弄清楚它为什么会失败.
1> 小智..:
我遇到了同样的问题.问题是我已经声明了url,但是在做httpget时,我意识到url没有分配任何值:
可能的情况:示例:private yourUrl:string;
并在您的http调用中:return this.http.get(this.yourUrl,{headers:this.headers})
2> 小智..:
看来您错误地声明了一个变量,从而使其变得未定义:请尝试以下操作
对于整洁的编码
interface User = {
id: number;
userName: string;
password: string;
}
user: User;
同时更正此行
private usersUrl: 'http://localhost:8080/users';
至
private usersUrl = 'http://localhost:8080/users';
这可能是问题所在