【问题标题】:Angular TS Error TS1109角度 TS 错误 TS1109
【发布时间】:2018-06-11 00:31:08
【问题描述】:

我在控制台中收到以下错误:

webpack: 正在编译... 10% 构建模块 0/1 模块 1 活动 ...p/shoppinglist2/src/app/app.module.tsERROR 在 src/app/meal.service.ts(46,56):错误 TS1109:预期表达式。

日期:2017-12-31T09:55:50.224Z
哈希:8003d6d8f334085afa7f 时间:267ms 块 {inline} inline.bundle.js (inline) 5.79 kB [entry] 块 {main} main.bundle.js (main) 73.1 kB [初始] [渲染] 块 {polyfills} polyfills.bundle.js (polyfills) 558 kB [初始] 块 {styles} styles.bundle.js (styles) 456 kB [初始] 块 {vendor} vendor.bundle.js(供应商)11.3 MB [初始]

webpack:编译成功。

我没有看到问题。该代码基于来自 https://angular.io/tutorial/toh-pt6 的 Angular HTTP 示例。 我正在使用 Angular ^5.0.0,rxjs ^5.5.2

meal.service.ts 中的代码:

import { Injectable }              from '@angular/core';
import { Observable }              from 'rxjs/Observable';
import { catchError, map, tap }    from 'rxjs/operators';
import { of }                      from 'rxjs/observable/of';
import { HttpClient, HttpHeaders,
         HttpParams }              from '@angular/common/http';

import { MessageService }          from './message.service';
import { Meal, oneMeal, Meals }    from './meal';

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

@Injectable()
export class MealService {

  constructor(
    private http: HttpClient,
    private messageService: MessageService
  ) { };

  private mealUrl = 'http://192.168.178.11:1337/api/meal';

  private log(message: string) {
    this.messageService.add('MealService: ' + message);
  };

  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error)
      this.log(`${operation} failed: ${error.message}`);
      return of(result as T);
    };
  }

  getMeals (page:number): Observable<Meals> {
    let httpParams = new HttpParams().set('where', '%')
      .set('orderBy', 'meal_id')
      .set('page', page.toString())
      .set('items', '10');
    //this.messageService.add('Debug: ' + httpParams);
    return this.http.get<Meals>(this.mealUrl, { params: httpParams  })
      .pipe(
        tap(meals => this.log(`fetched ${meals.count} entries`)),
        catchError(this.handleError('getMeals', <Meals>)) // Line 46: the Error
      );
  };

  getMeal (id:number): Observable<oneMeal> {
    let httpParams = new HttpParams().set('id', id.toString());
    //this.messageService.add(`MealService: fetched meal_id=${id}`);
    return this.http.get<oneMeal>(this.mealUrl, { params: httpParams })
      .pipe(
        tap(meal => this.log(`fetched ${meal.data[0].meal_name}`))//,
        //catchError(this.handleError('getMeal', <oneMeal>))
      );
  }
}

【问题讨论】:

    标签: javascript angular rxjs


    【解决方案1】:

    您以错误的方式调用泛型方法,因此您 得到这个 -

    src/app/meal.service.ts(46,56) 中的错误:错误 TS1109:表达式 预计

    错误的方式

    catchError(this.handleError('getMeals', <Meals>)) // Line 46: the Error
    

    正确方法

    catchError(this.handleError<Meals>('getMeals'))
    

     getMeals (page:number): Observable<Meals> {
        let httpParams = new HttpParams().set('where', '%')
          .set('orderBy', 'meal_id')
          .set('page', page.toString())
          .set('items', '10');
        //this.messageService.add('Debug: ' + httpParams);
        return this.http.get<Meals>(this.mealUrl, { params: httpParams  })
          .pipe(
            tap(meals => this.log(`fetched ${meals.count} entries`)),
            catchError(this.handleError<Meals>('getMeals')) // Line 46: the Error
          );
      };
    

    【讨论】:

    • 如果我这样做,我会收到此错误:ERROR in src/app/meal.service.ts(43,5): error TS2322: Type 'Observable&lt;{} | Meals&gt;' is not assignable to type 'Observable&lt;Meals&gt;'. Type '{} | Meals' is not assignable to type 'Meals'. Type '{}' is not assignable to type 'Meals'. Property 'count' is missing in type '{}'. src/app/meal.service.ts(46,56): error TS2345: Argument of type 'typeof Meals' is not assignable to parameter of type 'Meals'. Property 'count' is missing in type 'typeof Meals'.
    【解决方案2】:

    如果您检查您所引用的文档中的 handleError 函数,您会注意到它期望接收一个参数,

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

    但是在你的代码中,你使用了错误的handleError函数。

    getMeals (page:number): Observable<Meals> {
        let httpParams = new HttpParams().set('where', '%')
          .set('orderBy', 'meal_id')
          .set('page', page.toString())
          .set('items', '10');
        //this.messageService.add('Debug: ' + httpParams);
        return this.http.get<Meals>(this.mealUrl, { params: httpParams  })
          .pipe(
            tap(meals => this.log(`fetched ${meals.count} entries`)),
            catchError(this.handleError('getMeals', <Meals>)) // Line 46: the Error
          );
      };
    

    这就是你得到这个的原因 - src/app/meal.service.ts(46,56) 中的错误:错误 TS1109:预期表达式。 所以试试这个 -

    catchError(this.handleError('getMeals'))

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 2023-02-03
      • 2016-06-19
      • 2016-06-19
      相关资源
      最近更新 更多