Angular开发邮件服务报错Property 'api' does not exist问题咨询
解决方案
错误原因
MyService 类中未提前声明 api 属性,就直接在方法中通过 this.api 调用,TypeScript 类型检测识别不到未声明的类属性,因此抛出“Property 'api' does not exist on type 'MyService'”错误。
修复方案
- 在
MyService类中声明api字符串属性,赋值为你自己的 Mailthis Email API 接口地址即可,标准格式为https://mailthis.to/你的绑定收件邮箱 - 可选优化:原代码将错误回调写在
map操作符参数中不生效,可改用catchError单独处理请求异常
完整修复后代码
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map, catchError } from 'rxjs/operators'; import { of } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class MyService { // 新增api属性声明,替换为你实际的Mailthis接口地址 private api: string = 'https://mailthis.to/你的实际收件邮箱'; constructor(private http: HttpClient) { } PostMessage(input: any) { return this.http.post(this.api, input, { responseType: 'text' }).pipe( map((response: any) => { return response ?? null; }), catchError((error: any) => { return of(error); }) ) } }
补充说明
如果需要适配开发、生产等多环境切换,也可以将接口地址定义在 Angular 项目的环境配置文件(environment.ts/environment.prod.ts)中,再引入到服务里使用,无需每次修改服务代码切换地址。
内容的提问来源于stack exchange,提问作者Luis Alejandro López de Anda
相关产品推荐
相关产品推荐

