Angular5 httpClient get:无法读取未定义的属性'toLowerCase'

Can*_*lla 7 httpclient angular angular5

我试图从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)
Run Code Online (Sandbox Code Playgroud)

我有一个调用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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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<User[]> {
    return this.http.get<User[]>(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<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // 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);
  }

}
Run Code Online (Sandbox Code Playgroud)

和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 { }
Run Code Online (Sandbox Code Playgroud)

我可以看到日志记录中显示的错误消息,所以它似乎是来自HttpClient的错误.但在将Http请求发送到服务器之前,我无法弄清楚它为什么会失败.

小智 11

我遇到了同样的问题.问题是我已经声明了url,但是在做httpget时,我意识到url没有分配任何值:

可能的情况:示例:private yourUrl:string;

并在您的http调用中:return this.http.get(this.yourUrl,{headers:this.headers})


小智 7

看来您错误地声明了一个变量,从而使其变得未定义:请尝试以下操作

对于整洁的编码

interface User = {
      id: number;
      userName: string;
      password: string;
  }

user: User;
Run Code Online (Sandbox Code Playgroud)

同时更正此行

private usersUrl: 'http://localhost:8080/users';
Run Code Online (Sandbox Code Playgroud)

private usersUrl =  'http://localhost:8080/users';
Run Code Online (Sandbox Code Playgroud)

这可能是问题所在


Mai*_*eck 0

我有同样的问题。正如@Canlla 所说,有必要将 url 变量的可见性从公共更改为私有。

奇怪的是,有什么东西正在改变它的价值!不管怎样,它必须是私有的,因为我们不需要在模板上访问它。

此外,就我而言,我需要添加 NgIf / NgElse 以避免在加载完成之前进行数据绑定:

<mat-list *ngIf="transactions | async; let transactions;else loading">
      <div *ngFor="let transaction of transactions">
        <h3 mat-subheader>{{ transaction.dueDate }}</h3>        
        <mat-list-item>
          <img matListAvatar src="https://source.unsplash.com/random/100x100" alt="...">
          <span matLine class="mat-body-2"> {{transaction.description}} </span>
          <p matLine class="col col-6 left-align">
            <span class="mat-body-1"> {{transaction.categoryName}} </span>
            <br>
            <span class="mat-caption"> {{transaction.accountName}} </span>
          </p>
          <p class="col col-6 right-align">
            <span class="mat-subheading">{{ transaction.amount | currency:'BRL':'symbol' }}</span>
          </p>
        </mat-list-item>       
      </div>
    </mat-list>

<ng-template #loading>Loading...</ng-template>
Run Code Online (Sandbox Code Playgroud)

所以在这里: <mat-list *ngIf="transactions | async; let transactions;else loading">

我有 *ngIf 和async管道来显示mat-list是否transactions已加载。下一个let user语句如果 true 创建一个本地模板变量,Angular 会从 Observable 中分配值。

否则else loading告诉 Angular 是否不满足显示加载模板的条件。

查看来自 @coryrylan 的这篇优秀文章:https://coryrylan.com/blog/angular-async-data-binding-with-ng-if-and-ng-else