Typescript 共享服务&x27;通过router.navigate方法加载组件时,NgOnInit中未调用s方法

Typescript 共享服务&x27;通过router.navigate方法加载组件时,NgOnInit中未调用s方法,typescript,rxjs,observable,angular6,sharedservices,Typescript,Rxjs,Observable,Angular6,Sharedservices,我有一个详细组件和子组件概述和联系人,我使用了一个共享服务来共享一个数组ImageMap,该数组ImageMap在初始化时从服务检索后由详细信息更新,并由子组件通过各自的init方法订阅和访问。当我导航到子组件时,在地址栏中手动键入地址,子组件的ngOnInit中用于设置共享服务的数组值的代码段将被加载,而在通过路由器导航时。单击按钮导航,除了ngOnInit中的该部分外,其他所有内容都将被加载。请帮我做这个。我哪里出错了? //帐户详细信息组件.html <h3>You selec

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

//帐户详细信息组件.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() { }
}
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})

   }
  }
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();
    }




}
//帐户概览组件.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() { }
}
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})

   }
  }
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();
    }




}
从'@angular/core'导入{Component,OnInit,Input,OnDestroy,NgZone};
从'@ng bootstrap/ng bootstrap'导入{NgbCarouselConfig};
从“rxjs/operators”导入{map};
从'@angular/common/http'导入{HttpClient};
从“@angular/Router”导入{ActivatedRoute,Router,ParamMap};
从“../datashare.service”导入{DatashareService};
从'rxjs/Subscription'导入{Subscription};
@组成部分({
选择器:“应用程序帐户概述”,
templateUrl:“./account overview.component.html”,
样式URL:['./帐户概览.component.css'],
提供者:[NgbCarouselConfig]
})
导出类AccountOverview组件实现OnInit、OnDestroy{
私人订阅:订阅=新订阅();
公共图像阵列;
公共影像地图;
公共错误消息;
公开选定的名称;
构造函数(config:NgbCarouselConfig,private\u http:HttpClient
,专用路由:ActivatedRoute,专用数据服务:DatashareService
,私人专区:NgZone){
//自定义此组件树使用的转盘的默认值
config.interval=2000;
config.keyboard=false;
config.pauseonhaver=false;
}
恩戈尼尼特(){
this.route.paramMap.subscribe((params:paramMap)=>
{
让name=params.get('name');
此。所选名称=名称;
console.log(此.selected_名称);
})
this.subscription.add(this.dataService.getData().subscripte(data=>{//{
this.imageArray=数据;
})
}))
}
恩贡德斯特罗(){
//取消订阅以确保没有内存泄漏
this.subscription.unsubscripte();
}
}

尝试返回在
DatashareService.ts
中可观察到的
dataObs$
,并将主题替换为行为主题

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() { }
}
从'rxjs/Rx'导入{BehaviorSubject};
导出类数据共享服务{
私有dataObs$=新行为主体({});
getData(){
返回此.dataObs$.asObservable();
}
更新数据(数据){
this.dataObs$.next(数据);
}
构造函数(){}
}

使用Behavior Subject导致子组件中的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() { }
}
从'rxjs/Rx'导入{ReplaySubject};
导出类数据共享服务{
私有数据对象$=新的ReplaySubject(1);
getData(){
返回此.dataObs$.asObservable();
}
更新数据(数据){
this.dataObs$.next(数据);
}
构造函数(){}
}

尝试过这一点,结果仍然是控制台中的sameNo错误,当我浏览按钮时,单击它不会执行,当我在地址栏中按enter键刷新它时,它会执行。您的代码是否实际输入了ngOnInit方法?您可以通过将console.log()放在ngOnInit内最上面的代码行来检查这一点吗?是的,它会执行,除了该部分之外的所有内容都会执行,参数读取和console语句都会工作,只有这一部分不会得到renderokay,下一个问题。
console.log()
是否打印
this.subscription.add(this.dataService.getData().subscripte(data=>{…
)中的任何内容?您可以访问那里的
数据吗?