使用Angular中的服务方法传递组件之间的数据

发布于 2025-01-20 08:54:24 字数 2627 浏览 1 评论 0原文

我正在使用角度服务在组件之间传递数据。我希望此服务保存 4 个 ID uniId、schoolId、classId 和 StudentId。有 4 个组件:组件 1 设置 uniId,组件 2 使用 uniId 设置 schoolId,组件 3 使用 uniId 和 schoolId 设置 classId,组件 4 使用 uniId、schoolId 和 classId 设置 StudentId。 我想实现以下目标:

  1. 将所有 4 个 id 设置到服务中。
  2. 使用service,获取组件视图上的ids,并以Component1 Path -> 的形式用于导航组件2路径->组件3路径-> Component4 使用锚标记的路径(这样当我在第 3 页上时,我可以使用服务中的 id 导航到第 2 页。)

模型类

export interface GlobalData {
    uniId: number;
    schoolId: number;
    classId: number;
    studentId: number;
}

服务类

import { Injectable } from '@angular/core';
import { GlobalData } from 'src/models/GlobalData';
import { BehaviorSubject, Observable, Subject } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class GlobaldataService {
  private globalDataSubject = new Subject<GlobalData>();

  constructor() { }

  public getGlobalData(): Observable<GlobalData> {
    return this.globalDataSubject.asObservable();
  }

  public setGlobalData(globalDataObj: GlobalData) {
    return this.globalDataSubject.next(globalDataObj);
  }

}

组件 3

globalDataObject: GlobalData;
uniId: number = 0;
schoolId: number = 0;
constructor(private router: Router, private route: ActivatedRoute, private globalDataService: GlobaldataService) {
  }
ngOnInit() { 
this.route.queryParams.subscribe(params => {
        this.uniId = params['uniId'];
        this.schoolId = params['schoolId'];
      })
      this.globalDataService.setGlobalData({
        uniId: this.uniId, 
        schoolId: this.schoolId,
        classId: 0,
        studentId: 0
      });
      this.globalDataService.getGlobalData().subscribe(x =>    
        this.globalDataObject = x) 
}

组件 3 视图

<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
            <a [routerLink]="['/unis']">Universities</a>
        </li>
<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
            <a [routerLink]="['/schools']" [queryparams]="{uniId: this.uniId}">Schools</a>
</li>
<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
            <a [routerLink]="['/classes']">Classes</a>
        </li>

在组件 3 中,当我单击第一个链接时,它将显示所有大学,当我单击第二个链接时,它将显示该大学中已选择 id 的所有学校,并且班级将 npt 导航到任何内容,因为组件 3 是班级。

我没有在服务中获取数据,并且导航不会连接 id。 任何人都可以帮忙解决这个问题吗?

I am using a angular service to pass the data between components. I would like this service to hold the 4 ids uniId, schoolId, classId and studentId. There are 4 components: Component 1 setting uniId, Component2 setting schoolId using uniId, Component 3 setting classId using uniId and schoolId and Component 4 setting studentId using uniId, schoolId and classId.
I want to achieve following:

  1. Setting all the 4 ids into the service.
  2. Using service, get the ids on the view of the component and use it for navigation in the form of Component1 Path -> Component2 Path -> Component3 Path -> Component4 Path using the anchor tag (so that when I am on page 3 I can navigate to page 2 using the id from service.)

Model class

export interface GlobalData {
    uniId: number;
    schoolId: number;
    classId: number;
    studentId: number;
}

Service Class

import { Injectable } from '@angular/core';
import { GlobalData } from 'src/models/GlobalData';
import { BehaviorSubject, Observable, Subject } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class GlobaldataService {
  private globalDataSubject = new Subject<GlobalData>();

  constructor() { }

  public getGlobalData(): Observable<GlobalData> {
    return this.globalDataSubject.asObservable();
  }

  public setGlobalData(globalDataObj: GlobalData) {
    return this.globalDataSubject.next(globalDataObj);
  }

}

Component 3

globalDataObject: GlobalData;
uniId: number = 0;
schoolId: number = 0;
constructor(private router: Router, private route: ActivatedRoute, private globalDataService: GlobaldataService) {
  }
ngOnInit() { 
this.route.queryParams.subscribe(params => {
        this.uniId = params['uniId'];
        this.schoolId = params['schoolId'];
      })
      this.globalDataService.setGlobalData({
        uniId: this.uniId, 
        schoolId: this.schoolId,
        classId: 0,
        studentId: 0
      });
      this.globalDataService.getGlobalData().subscribe(x =>    
        this.globalDataObject = x) 
}

Component 3 View

<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
            <a [routerLink]="['/unis']">Universities</a>
        </li>
<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
            <a [routerLink]="['/schools']" [queryparams]="{uniId: this.uniId}">Schools</a>
</li>
<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
            <a [routerLink]="['/classes']">Classes</a>
        </li>

In Component 3, when I click on first link it would show all unis, when I click on the second link it would show all schools in the uni whose id is selected and classes would npt navigate to anything as Component 3 is Classes.

I am not getting data in service and the navigation does not concatenate ids.
Can anyone please help on this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谎言 2025-01-27 08:54:24

三个问题:

  1. 您在参数订阅之外设置全局数据。

  2. 除非您使用async管道,否则可观察订阅不会触发更改检测。因此,您需要使用 ChangeDetectorRef 强制执行。

  constructor(private changeDetectorRef: ChangeDetectorRef) {}

  async ngOnInit() {
    this.route.queryParams.subscribe((params) => {
      this.uniId = params['uniId'];
      this.schoolId = params['schoolId'];
      this.globalDataService.setGlobalData({
        uniId: this.uniId,
        schoolId: this.schoolId,
        classId: 0,
        studentId: 0,
      });
      this.globalDataService.getGlobalData().subscribe((x) => {
        this.globalDataObject = x;
        this.changeDetectorRef.detectChanges();
      });
    });
  }
  1. queryParams 有一个大写的 P
...
<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
  <a [routerLink]="['/schools']" [queryParams]="{ uniId: this.uniId }"
    >Schools</a
  >
</li>
...

这都可以更简单地重写,如果您只是设置和获取值,则不需要可观察量。

服务

@Injectable({
  providedIn: 'root',
})
export class GlobaldataService {
  globalData?: GlobalData;
}

组件 3

  get uniId() {
    return this.globalDataService.globalData?.uniId;
  }

  constructor(
    private route: ActivatedRoute,
    private globalDataService: GlobaldataService
  ) {}
  ngOnInit() {
    const params = this.route.snapshot.queryParams;
    this.globalDataService.globalData = {
      uniId: params['uniId'],
      schoolId: params['schoolId'],
      classId: 0,
      studentId: 0,
    };
  }
<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
  <a [routerLink]="['/unis']">Universities</a>
</li>
<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
  <a [routerLink]="['/schools']" [queryParams]="{ uniId }">Schools</a>
</li>
<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
  <a [routerLink]="['/classes']">Classes</a>
</li>

尽管我认为当您可以注入服务时通过模板传递 queryParams 没有任何意义。

Three problems:

  1. You're setting your global data outside of your params subscription.

  2. Observable subscriptions don't trigger change detection unless you're using the async pipe. So you need to force it with ChangeDetectorRef.

  constructor(private changeDetectorRef: ChangeDetectorRef) {}

  async ngOnInit() {
    this.route.queryParams.subscribe((params) => {
      this.uniId = params['uniId'];
      this.schoolId = params['schoolId'];
      this.globalDataService.setGlobalData({
        uniId: this.uniId,
        schoolId: this.schoolId,
        classId: 0,
        studentId: 0,
      });
      this.globalDataService.getGlobalData().subscribe((x) => {
        this.globalDataObject = x;
        this.changeDetectorRef.detectChanges();
      });
    });
  }
  1. queryParams has a capital P
...
<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
  <a [routerLink]="['/schools']" [queryParams]="{ uniId: this.uniId }"
    >Schools</a
  >
</li>
...

This can all be rewritten much simpler, there's no need for observables if you're simply setting and getting values.

Service

@Injectable({
  providedIn: 'root',
})
export class GlobaldataService {
  globalData?: GlobalData;
}

Component 3

  get uniId() {
    return this.globalDataService.globalData?.uniId;
  }

  constructor(
    private route: ActivatedRoute,
    private globalDataService: GlobaldataService
  ) {}
  ngOnInit() {
    const params = this.route.snapshot.queryParams;
    this.globalDataService.globalData = {
      uniId: params['uniId'],
      schoolId: params['schoolId'],
      classId: 0,
      studentId: 0,
    };
  }
<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
  <a [routerLink]="['/unis']">Universities</a>
</li>
<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
  <a [routerLink]="['/schools']" [queryParams]="{ uniId }">Schools</a>
</li>
<li class="dds__breadcrumb__item" [routerLinkActive]="['link-active']">
  <a [routerLink]="['/classes']">Classes</a>
</li>

Although I don't see a point in passing queryParams through the template when you can just inject the service.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文