【问题标题】:Angular 6 ActivatedRouteSnapshot Service FirebaseAngular 6 ActivatedRouteSnapshot 服务 Firebase
【发布时间】:2023-03-27 11:54:01
【问题描述】:

想使用我的详细信息组件的 ID 将数据保存在 Firebase 中(pah: '/patient/:id'

为了保存数据,我在 data-service 中写了这个:

 createNewTumeur(newTumeur: Tumeur) 
 {
 const id = this.route.snapshot.params['id'];
 console.log(id);
 this.tumeurs.push(newTumeur);
 firebase.database().ref('/patients/'+id).child("tumeur").update(this.tumeurs);
 this.tumeurSubject.next(this.tumeurs);

但我不能拥有 id 的值...请问有什么问题?

【问题讨论】:

  • 为什么不能保存?浏览器控制台是否显示任何错误?请提供更多详细信息。
  • 控制台说id未定义
  • 如果我写这个我可以保存在好地方 firebase.database().ref('/patients/'0).child("tumeur").update(this.tumeurs);
  • 所以我猜你的console.log(id); 显示未定义。您的 URL 是否包含 id 属性?这个组件的路由是什么样子的?
  • 是的,我的 URL 包含 id 属性我的这个组件的路由是:{ path: 'patients/:id', canActivate: [AuthGuardService], component: SinglePatientComponent },

标签: angular firebase firebase-realtime-database snapshot


【解决方案1】:

// my.component.ts

import { ActivatedRoute } from '@angular/router';
import { MyDataService } from './my-data.service';

constructor(private route: ActivatedRoute, private dataService: MyDataService)

createNewTumeur(newTumeur: Tumeur) {
  const id = this.route.snapshot.params['id'];
  console.log(id);
  this.dataService.createNewTumeur(id)
  // And then add the logic into your dataService
}

注意:只能在组件中获取路由器参数,不能在服务中获取。

这是因为服务是属于根注入器的单例。 您可以将路由参数发送到您的服务或在您的组件中提供您的服务(但是这会创建另一个服务实例,我个人不推荐这样做)。

Component({
  ...
  providers: [MyDataService]
})
export class MyComponent { ... }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-01-10
  • 2019-03-04
  • 2018-11-24
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 2018-01-18
  • 2019-01-08
相关资源
最近更新 更多