【问题标题】:Function lacks ending return statement and return type does not include 'undefined' (2366)函数缺少结束返回语句且返回类型不包括“未定义”(2366)
【发布时间】:2020-12-03 17:35:29
【问题描述】:

我正在创建 Angular 通用服务以使用 HTTP 与后端通信 创建以下动态函数以使用标题

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { URLSearchParams } from '@angular/http';
import { Router } from '@angular/router';
import { from, Observable, of, throwError } from 'rxjs';
import { map, catchError, timeout } from 'rxjs/operators';
import * as _ from 'lodash';

@Injectable()
export class CommonAPIService {

    private _adminHeaders = new HttpHeaders({
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    })
    constructor(private http: HttpClient,
        public router: Router) {

    }

    public getAdminHeaders(): HttpHeaders {
        if (localStorage.getItem('access_token')) {
            this._adminHeaders = new HttpHeaders({
                'Authentication': localStorage.getItem('access_token') || 'null'
            });
            return this._adminHeaders;
        }
        else {
            this._adminHeaders = new HttpHeaders({
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            })
        }
       }
    }
}

在公共 getAdminHeaders 函数中出现此错误: 函数缺少结束返回语句且返回类型不包含'undefined'

我还从 Angular 通用库导入 httpheader

【问题讨论】:

  • 您不会在else 子句中返回任何内容。

标签: javascript angular


【解决方案1】:

试试这个。 getAdminHeaders 期待返回类型(HttpHeaders) 但在 else 子句中你没有返回任何东西。这就是你得到 ts 错误的原因

public getAdminHeaders(): HttpHeaders { // <-- declared return type
  if (localStorage.getItem('access_token')) {
    this._adminHeaders = new HttpHeaders({
      'Authentication': localStorage.getItem('access_token') || 'null'
    });
  } else {
    this._adminHeaders = new HttpHeaders({
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    })
  }
  return this._adminHeaders;
}

【讨论】:

    猜你喜欢
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2022-09-30
    • 2021-11-13
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多