1

我有一个详细组件和子组件概述和联系方式,我使用共享服务来共享一个数组 ImageMap,该数组在初始化时从服务中检索后由详细信息更新,并由子组件在其各自的 init 方法上订阅和访问。当我导航到子组件时,在地址栏中手动键入地址时,子组件的 ngOnInit 中的片段以设置共享服务中的数组值被加载,而在通过 router.navigate 导航时单击按钮,除了该部分NgOnInit 其他所有内容都会被加载。请帮助我。我哪里出错了?

//账户明细component.html

<h3>You selected brand {{item_name}}</h3>
<p>
    <button (click)="showOver()" class="btn btn-primary">Overview</button>
    <button (click)="showCon()" class="btn btn-info">Contact</button>
</p>
<router-outlet></router-outlet>
<button (click)="gotoAccounts()" class="btn btn-warning">Back</button>

//数据共享服务.ts

import { Injectable } from '@angular/core';
import { Subject,BehaviorSubject } from 'rxjs/Rx';

@Injectable({
    providedIn: 'root'
})
export class DatashareService {

  private dataObs$ =  new Subject();



     getData() {
        return this.dataObs$;
                }

updateData(data) {
    this.dataObs$.next(data);
                  }

 constructor() { }
}

//账户明细组件.ts

import { Component, OnInit} from '@angular/core';
import { ActivatedRoute,Router,ParamMap } from '@angular/router';
import { ImageFetchService } from '../image-fetch.service';
import { DatashareService } from '../datashare.service';

@Component({
        selector: 'app-account-detail',
        templateUrl: './account-detail.component.html',
        styleUrls: ['./account-detail.component.css']
           })
export class AccountDetailComponent implements OnInit {

public item_id;
public item_name;
public imageMap;
public errorMsg;
constructor(private route: ActivatedRoute,private router:Router,private 
imageService: ImageFetchService,
private dataService: DatashareService) { }

ngOnInit() {

//let id = parseInt(this.route.snapshot.paramMap.get('id'));
//this.item_id=id;

this.route.paramMap.subscribe((params: ParamMap)=>
{
  let id = parseInt(params.get('id'));
  this.item_id=id;
  let sel_name = params.get('name');
  this.item_name=sel_name;
  console.log(this.item_id,this.item_name);
}  )

 this.imageService.getImages().subscribe(data =>{ this.imageMap=data;

 this.dataService.updateData(this.imageMap);},
                                              error => this.errorMsg=error);




 }



  showOver()
  {
               let sel_name= this.item_name?this.item_name:null;

                this.router.navigate(['overview',{"name":sel_name}],
                {relativeTo:this.route})


   }

   showCon()
   {
       let sel_name= this.item_name?this.item_name:null;

       this.router.navigate(['contact',{"name":sel_name}],
       {relativeTo:this.route})

   }
  }

//账户总览Component.ts

import { Component, OnInit,Input,OnDestroy,NgZone } from '@angular/core';
import {NgbCarouselConfig} from '@ng-bootstrap/ng-bootstrap';
import {map} from 'rxjs/operators';
import {HttpClient} from '@angular/common/http';
import { ActivatedRoute,Router,ParamMap } from '@angular/router';
import { DatashareService } from '../datashare.service';
import { Subscription } from 'rxjs/Subscription';


@Component({
  selector: 'app-account-overview',
  templateUrl: './account-overview.component.html',
  styleUrls: ['./account-overview.component.css'],
  providers: [NgbCarouselConfig]
})
export class AccountOverviewComponent implements OnInit,OnDestroy {
private subscription: Subscription = new Subscription();
public imageArray;
 public imageMap;
 public errorMsg;
 public selected_name;
  constructor(config: NgbCarouselConfig, private _http: HttpClient
  ,private route:ActivatedRoute,private dataService: DatashareService
  ,private zone:NgZone) {
    // customize default values of carousels used by this component tree
    config.interval = 2000;
    config.keyboard = false;
    config.pauseOnHover = false;
  }

  ngOnInit() {

   this.route.paramMap.subscribe((params: ParamMap)=>
        {
            let name =params.get('name');
            this.selected_name=name;
            console.log(this.selected_name);
        })

        this.subscription.add(this.dataService.getData().subscribe(data => { //<== added this

            this.zone.run(()=>{
                this.imageArray = data;
            })

        }))







  }

  ngOnDestroy() {
        // unsubscribe to ensure no memory leaks
        this.subscription.unsubscribe();
    }




}
4

2 回答 2

1

使用 BehaviourSubject 会导致子组件中的 subscribe 方法触发两次,首先是初始值 {},然后是最后更新的值。所以我把它改成了不需要初始值的 ReplaySubject。

import { ReplaySubject } from 'rxjs/Rx';

export class DatashareService {

    private dataObs$ = new ReplaySubject<any>(1);

    getData() {
        return this.dataObs$.asObservable();
    }

    updateData(data) {
        this.dataObs$.next(data);
    }

    constructor() { }
}
于 2018-08-06T09:26:29.700 回答
0

尝试dataObs$在您的中以 Observable 的形式返回,DatashareService.ts并用 BehaviorSubject 替换您的主题。

import { BehaviorSubject } from 'rxjs/Rx';

export class DatashareService {

    private dataObs$ = new BehaviorSubject<any>({});

    getData() {
        return this.dataObs$.asObservable();
    }

    updateData(data) {
        this.dataObs$.next(data);
    }

    constructor() { }
}
于 2018-08-06T06:06:29.720 回答