簡體   English   中英

我們如何在Angular 2+中的模塊內發送數據

[英]how can we send data within modules in Angular 2+

我被困在從一模塊向另一模塊發送一些小的數據塊中。 我不會將這些數據存儲在查詢參數中或某些瀏覽器級別的存儲或緩存中。 我可以使用哪些選項,或者angular有什么機制可以做到這一點而無需重新加載我的應用程序。

服務是為相同而設計的(依賴注入)

@Injectable()
export class SomeService {
//define a variable
someVariable = "xyz";
}

在組件的父模塊或根模塊(app.module.ts)中提供此服務

將服務注入組件

one.component.ts
constructor(private someService: SomeService) {

}

//在此處更新變量

this.someService.someVariable = "Value Changed"

two.component.ts
constructor(private someService: SomeService) {}
// updated variable can be accessed here
console.log(this.someService.someVariable);

您可以創建共享服務。 然后,您可以在兩個模塊中訂閱該服務並共享數據。

例如:

這是我的http服務,在模塊之間共享

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { APIUrls } from '../Enums/api-url.enum';
import { HttpResponse } from 'selenium-webdriver/http';
import { SessionStorageService } from './session-storage.service';
import { SessionStorageKeys } from '../Enums/session-storage-keys.enum';

@Injectable()
export class HttpService {

  constructor(private _http: HttpClient, private _sessionService: SessionStorageService) {

  }

  public PostRequest(apiURL: string, body: any): Observable<HttpResponse> {
    let auth_token = this._sessionService.get(SessionStorageKeys.AUTH_TOKEN);
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + auth_token
      })
    };
    return this._http.post(APIUrls.BaseURL + apiURL, body, httpOptions);
  }

  public GetRequest(apiURL: string): Observable<HttpResponse> {
    let auth_token = this._sessionService.get(SessionStorageKeys.AUTH_TOKEN);
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + auth_token
      })
    };
    return this._http.get(APIUrls.BaseURL + apiURL, httpOptions);
  }

  private _transformRequest(obj: any): any {
    var str = [];
    for (var p in obj)
      if (obj.hasOwnProperty(p)) {
        str.push(encodeURIComponent(p) + ":" + encodeURIComponent(obj[p]));
      }
    return str;
  }

}

我在app.module.ts的 provider數組中添加了此服務

然后將此服務注入到不同模塊中的組件的構造函數中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM