【问题标题】:Getting "Property 'route' does not exist on type 'typeof" using angular10使用角度 10 在类型“typeof”上不存在“属性‘路由’
【发布时间】:2021-06-18 18:11:42
【问题描述】:

我正在尝试使用以下代码将数据从服务路由到组件。它显示错误

“类型 'typeof PaymentService'.ts 上不存在属性 'route'”

“声明静态属性路由”

import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { Router} from '@angular/router';
@Injectable({
  providedIn: 'root',
})

export class PaymentService {    
    constructor(private route:Router) { }
    static verifyPayment(payload: any) {
    const axios = require('axios');

let data = {
    'token': payload.token,
    'amount': payload.amount,

 };

axios.post(environment.api_url+"set_appointment_with_payment", data)
    .then(response => {
        if(response.data.paymentStatus=== "Completed"){
            this.route.navigate('/Bill');
        }else{
            alert('Something went wrong! Please try again.');
        }
        
    })
    .catch(error => {
        console.log(error);
    });
}
}

【问题讨论】:

  • 无法从静态方法中获取实例属性

标签: typescript service axios angular10


【解决方案1】:

从构造函数中调用消息不是一个好习惯,但你可以这样做

 export class PaymentService {   

  static _route:Router;

  constructor(private route:Router) { 
     PaymentService._route = route;
  }

那么您只能在初始化后在静态方法中使用_route 对象。

然后在你的静态方法中使用它而不是this.route

        PaymentService._route.navigate('/Bill');

【讨论】:

  • 感谢您的回答。你能指定这里应该初始化什么吗?我只需要使用 this._route.navigate(['/Bill']); 导航到另一个页面;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
  • 2020-10-24
  • 2019-06-30
  • 1970-01-01
  • 2020-10-04
  • 2020-08-19
  • 2017-11-06
相关资源
最近更新 更多