最好创建一个服务,然后在其中设置值,并在所需的视图/组件中,从服务中获取值。如果您正在使用服务方法,并且在某些时候,如果页面由于任何原因而刷新,您可以简单地检查ID是否存在于服务中&如果需要,可以轻松地重定向到所需的视图。我不建议使用本地存储。
比如,创建一个服务说S。你有组件A,B& C.在组件A中,在服务S中设置所需的id,并且可以在B&amp ;;中访问该id值。 C注入B& B中的服务C。
的 app.module.ts 强>
import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { NgModule } from '@angular/core'; import { AppRoutesModule } from './app.routes'; import { AppComponent } from './app.component'; import { AComponent } from './acomponent.ts'; import { BComponent } from './bcomponent.ts'; import { CComponent } from './ccomponent.ts'; import { CustomService } from './custom.service'; @NgModule({ declarations: [ AppComponent, AComponent, BComponent, CComponent ], imports: [ BrowserModule, BrowserAnimationsModule, AppRoutesModule, ], providers: [ CustomService ], bootstrap: [AppComponent] }) export class AppModule { }
的 custom.service.ts 强>
import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { retry, catchError } from 'rxjs/operators'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; @Injectable({ providedIn: 'root' }) export class CustomService { user_id: any; fetchDataURL = "http://localhost:3000/api/some-link"; // Set data setUserId(id) { this.user_id = id; } // Fetch data getUserId() { return this.user_id; } // Fetch data which contains "user_id" fetchData(): Observable<any> { return this._http.get<any>(this.fetchDataURL, httpOptions) .pipe( retry(1), catchError(this.handleError) ); } // Error handler - you can customize this accordingly handleError(error) { let errorMessage = ''; if (error.error instanceof ErrorEvent) { // client-side error errorMessage = `Error: ${error.error.message}`; } else { // server-side error errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`; } return throwError(errorMessage); } }
的 a.component.ts 强>
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { CustomService } from './custom-service-location'; @Component({ selector: 'component-a', templateUrl: './a.component.html' }) export class AComponent implements OnInit { fetchedData: any; constructor(private customService: CustomService) {} ngOninit() { this.getData(); } // Fetch data getData() { this.customService.getData() .subscribe((data) => { console.log(data); this.fechedData = data; this.customService.setUserId(data.user_id); // Passing the user id to service }, (error) => { // logic to handle error accordingly }); } }
的 b.component.ts 强>
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { CustomService } from './custom-service-location'; @Component({ selector: 'component-b', templateUrl: './b.component.html' }) export class BComponent implements OnInit { user_id: any; constructor(private customService: CustomService, private router: Router) {} ngOninit() { this.getData(); } // Fetch user id from service getUserData(id) { this.customService.getUserId() .subscribe((data) => { this.user_id = data.user_id; if(this.user_id == null) { this.router.navigate(['/component-a-route']) // If the id is lost on some page refresh, redirect back to the needed page } }, (error) => { // logic to handle error accordingly }); } someOtherFunction() { // some other function with some other logic } }
正如您在上面所看到的,有一个主要的“app”模块,两个组件a&amp; b和服务文件。在组件A中,您调用函数fetchData,其中返回“user_id”(假设),您使用“setUserId()”方法在自定义服务中设置user_id,然后您可以使用“getUserId”在组件b中获取它()“ 方法。
我希望以上内容能够清楚地表明这一点。它有助于。