How do I pass data to Angular routed components?

前端 未结 16 1102
挽巷
挽巷 2020-11-22 08:03

In one of my Angular 2 routes\'s templates (FirstComponent) I have a button

first.component.html

相关标签:
16条回答
  • 2020-11-22 08:43

    You can use BehaviorSubject for sharing data between routed components. A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A Subject doesn't hold a value.

    In the service.

    @Injectable({
      providedIn: 'root'
    })
    export class CustomerReportService extends BaseService {
      reportFilter = new BehaviorSubject<ReportFilterVM>(null);
      constructor(private httpClient: HttpClient) { super(); }
    
      getCustomerBalanceDetails(reportFilter: ReportFilterVM): Observable<Array<CustomerBalanceDetailVM>> {
        return this.httpClient.post<Array<CustomerBalanceDetailVM>>(this.apiBaseURL + 'CustomerReport/CustomerBalanceDetail', reportFilter);
      }
    }
    

    In the component you can subscribe to this BehaviorSubject.

    this.reportService.reportFilter.subscribe(f => {
          if (f) {
            this.reportFilter = f;
          }
        });
    

    Note: Subject won't work here, Need to use Behavior Subject only.

    0 讨论(0)
  • 2020-11-22 08:44

    I this the other approach not good for this issue. I thing the best approach is Query-Parameter by Router angular that have 2 way:

    Passing query parameter directly

    With this code you can navigate to url by params in your html code:

    <a [routerLink]="['customer-service']" [queryParams]="{ serviceId: 99 }"></a>
    

    Passing query parameter by Router

    You have to inject the router within your constructor like:

    constructor(private router:Router){
    
    }
    

    Now use of that like:

    goToPage(pageNum) {
        this.router.navigate(['/product-list'], { queryParams: { serviceId: serviceId} });
    }
    

    Now if you want to read from Router in another Component you have to use of ActivatedRoute like:

    constructor(private activateRouter:ActivatedRouter){
    
    }
    

    and subscribe that:

      ngOnInit() {
        this.sub = this.route
          .queryParams
          .subscribe(params => {
            // Defaults to 0 if no query param provided.
            this.page = +params['serviceId'] || 0;
          });
      }
    
    0 讨论(0)
  • 2020-11-22 08:45

    Pass using JSON

      <a routerLink = "/link"
       [queryParams] = "{parameterName: objectToPass| json }">
             sample Link                   
      </a>
    
    0 讨论(0)
  • 2020-11-22 08:47

    use a shared service to store data with a custom index. then send that custom index with queryParam. this approach is more flexible.

    // component-a : typeScript :
    constructor( private DataCollector: DataCollectorService ) {}
    
    ngOnInit() {
        this.DataCollector['someDataIndex'] = data;
    }
    
    // component-a : html :
    <a routerLink="/target-page" 
       [queryParams]="{index: 'someDataIndex'}"></a>
    

    .

    // component-b : typeScript :
    public data;
    
    constructor( private DataCollector: DataCollectorService ) {}
    
    ngOnInit() {
        this.route.queryParams.subscribe(
            (queryParams: Params) => {
                this.data = this.DataCollector[queryParams['index']];
            }
        );
    }
    
    0 讨论(0)
提交回复
热议问题