简体   繁体   English

为什么我不能在 function 中使用路由器 object 为我的 Angular 服务中的 then() CRUD 删除操作定义?

[英]Why I can't use the Router object inside a function definied for the then() of a CRUD delete operation into my Angular service?

I am working on an Angular project and I have the following problem\doubt trying to use a Router class to navigate to a specifc page from the inside of a service class.我正在研究 Angular 项目,但我遇到以下问题\怀疑尝试使用路由器class 从服务 class 内部导航到特定页面。 I will try to explain my problem in details.我将尝试详细解释我的问题。

Basically I have this service class:基本上我有这个服务class:

@Injectable({
  providedIn: 'root'
})
export class PatientService {

 

  constructor(
              private firestore: AngularFirestore,
              private router: Router
             ) { }

    ........................................................................
    ........................................................................
    ........................................................................

  deletePatient(patientId) {
    console.log("deletePatient() START. patientId: " + patientId);
    this.firestore
        .collection("patients")
        .doc(patientId)
        .delete()
        .then(async function(docRef) {
          console.log("Patient successfully deleted!");
          //this.router.navigate(['/patients-list']);

        })
        .catch(function(error) {
          console.error("Error deleting document with ID: ", patientId);
          console.log("ERROR: ", error);

          // TODO: NAVIGATE ON THE USER DETAILS PASSING A PARAMETHER IN ORDER TO PRINT AN ERROR MESSAGE
        });

        this.router.navigate(['/patients-list']);
    
  }
}

As you can see I am injecting private router: Router into the constructor and then I use it into the deletePatient() method.如您所见,我将私有路由器:路由器注入构造函数,然后将其用于deletePatient()方法。

So as it is it works fine and it redirect me to the page specified by the patients-list route but this is not the correct behavior because I want to redirect to this page if and only if the patient was correctly deleted on my Firestore DB.因此它工作正常,它将我重定向到患者列表路由指定的页面,但这不是正确的行为,因为当且仅当患者在我的 Firestore 数据库中被正确删除时,我才想重定向到此页面。 So in theory this navigation should happen inside the function defined for the then() (afther that it print in the console the message "Patient successfully deleted.").所以理论上这个导航应该发生在为then()定义的 function 中(然后它在控制台中打印消息“Patient successfully deleted.”)。

The problem is that doing in this way:问题是这样做:

  deletePatient(patientId) {
    console.log("deletePatient() START. patientId: " + patientId);
    this.firestore
        .collection("patients")
        .doc(patientId)
        .delete()
        .then(async function(docRef) {
          console.log("Patient successfully deleted!");
          this.router.navigate(['/patients-list']);

        })
        .catch(function(error) {
          console.error("Error deleting document with ID: ", patientId);
          console.log("ERROR: ", error);

          // TODO: NAVIGATE ON THE USER DETAILS PASSING A PARAMETHER IN ORDER TO PRINT AN ERROR MESSAGE
        });

        //this.router.navigate(['/patients-list']);
    
  }

It doesn't redirect me and I obtain the following error message into the Chrome console:它不会重定向我,我在 Chrome 控制台中收到以下错误消息:

ERROR:  TypeError: Cannot read property 'router' of undefined
    at patient.service.ts:104
    at Generator.next (<anonymous>)
    at tslib.es6.js:74
    at new ZoneAwarePromise (zone-evergreen.js:960)
    at __awaiter (tslib.es6.js:70)
    at patient.service.ts:102
    at ZoneDelegate.invoke (zone-evergreen.js:364)
    at Object.onInvoke (core.js:27504)
    at ZoneDelegate.invoke (zone-evergreen.js:363)
    at Zone.run (zone-evergreen.js:123)

Why from the inside of the function defined for the then() case the rotuter object is not avaible.为什么从为then()案例定义的 function 内部, rotuter object 不可用。 Looking on the private router: Router injetion of my service constructor in this case the IDE say to me:查看私有路由器:在这种情况下,我的服务构造函数的路由器注入 IDE 对我说:

Property 'router' is declared but its value is never read.ts(6138)声明了属性“路由器”,但它的值永远不会被读取。ts(6138)

So it seems that someway from the inside of this function the this.router property is not accessible.所以似乎从这个 function 的内部, this.router属性是不可访问的。

Why?为什么? What am I missing?我错过了什么? How can I fix this problem in order to obtain the correct behavior?如何解决此问题以获得正确的行为? (I want to navigate to my /patients-list route in case of a correct patient delete action (the then()) or to an error page in case there are problem deleting the patient (the catch()) (如果有正确的患者删除操作(then()),我想导航到我的/patients-list路线,或者在删除患者时出现问题(catch())导航到错误页面

When you use an inline function, this refers to the function call context instead of your class instance.当您使用内联 function 时, this指的是 function 调用上下文而不是您的 class 实例。

Replace this:替换这个:

.then(async function(docRef) {
          console.log("Patient successfully deleted!");
          this.router.navigate(['/patients-list']);

 })
.catch(function(error) {

With an arrow function:用箭头 function:

.then((docRef) => {
          console.log("Patient successfully deleted!");
          this.router.navigate(['/patients-list']);

})
.catch((error) => {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在我的angular 2打字稿代码中不能使用indexOf函数? - Why can I not use the indexOf function in my angular 2 typescript code? Angular 4:为什么我不能在ngOnInit()中调用公共函数? - Angular 4: why can't I call a public function in my ngOnInit()? 为什么我的路由器导航 function 在 angular 8 中不起作用? - Why my router navigate function doesn't work in angular 8? 我可以在服务内使用小吃店吗? - Can I use a snackbar inside my service? 我使用 angular 路由器,不能使用 path:'**' 404 页面 - I use angular router and can't use path:'**' for 404 page 如何在 datatables.net 的 table.on() function 中使用 Angular 注入服务 - How can I use an Angular injected service inside a table.on() function of datatables.net 在CRUD Angular应用中编写删除功能时,为什么在数组中不存在编译错误,显示属性_id? - While coding a delete function in CRUD Angular app, why does a compilation error show property _id doesn't exist in array? 为什么Angular2不能注入我的服务? - Why can't Angular2 inject my service? How can I use my logo slider JavaScript function inside an Angular component / TypeScript? - How can I use my logo slider JavaScript function inside an Angular component / TypeScript? 我无法访问角度2中的对象内部的对象属性 - I can't access object properties that are inside an object in angular 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM