Angular 切换时重新渲染组件

Angular 切换时重新渲染组件,angular,typescript,angular-material,Angular,Typescript,Angular Material,我有一个带开关的“导航栏”组件,每次切换时我都想重新更新我的“主页”组件。更新需要在navbar.comp.ts中的onChange()函数中进行 import { Component, OnInit, Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { AreaService} from '../_services/index'; @Inje

我有一个带开关的“导航栏”组件,每次切换时我都想重新更新我的“主页”组件。更新需要在navbar.comp.ts中的onChange()函数中进行

    import { Component, OnInit, Injectable } from '@angular/core';
    import { Router } from '@angular/router';
    import { AreaService} from '../_services/index';

    @Injectable()
    @Component({
      selector: 'app-nav-bar',
        templateUrl: 'navBar.component.html'
    })

    export class NavBarComponent implements OnInit {
        routeLinks: any[];
        activeLinkIndex = 2;
        color = 'warn';
        checked: boolean;

        constructor(private router: Router,
        private areaService: AreaService) {
          this.routeLinks = [
          {label: 'Profile', link: '/profile/', index: '0'},
          {label: 'Notification', link: '/notifications/', index: '1'},
          {label: 'Home', link: '', index: '2'},
          {label: 'My Cards', link: '/cards/', index: '3'},
          {label: 'Create a Card', link: '/post/', index: '4'},
          {label: 'Logout', link: '/login/', index: '5'},
        ];
        }
        onChange(value) {

           if (value.checked === true) {
             this.areaService.currentArea = 1;
           } else {
             this.areaService.currentArea = 0;
           }
        }
        ngOnInit() {
        }
    }
导航栏组件

    import { Component, OnInit, Injectable } from '@angular/core';
    import { Router } from '@angular/router';
    import { AreaService} from '../_services/index';

    @Injectable()
    @Component({
      selector: 'app-nav-bar',
        templateUrl: 'navBar.component.html'
    })

    export class NavBarComponent implements OnInit {
        routeLinks: any[];
        activeLinkIndex = 2;
        color = 'warn';
        checked: boolean;

        constructor(private router: Router,
        private areaService: AreaService) {
          this.routeLinks = [
          {label: 'Profile', link: '/profile/', index: '0'},
          {label: 'Notification', link: '/notifications/', index: '1'},
          {label: 'Home', link: '', index: '2'},
          {label: 'My Cards', link: '/cards/', index: '3'},
          {label: 'Create a Card', link: '/post/', index: '4'},
          {label: 'Logout', link: '/login/', index: '5'},
        ];
        }
        onChange(value) {

           if (value.checked === true) {
             this.areaService.currentArea = 1;
           } else {
             this.areaService.currentArea = 0;
           }
        }
        ngOnInit() {
        }
    }
然后我想在家里重新运行ngOnInit.comp.ts

    import { Component, OnInit, Injectable } from '@angular/core';
    import { Response } from '@angular/http';
    import { FormsModule } from '@angular/forms';
    import { Post, Area } from '../_models/index';
    import { PostService, AreaService, HttpService} from '../_services/index';


    @Injectable()
    @Component({
        templateUrl: 'home.component.html',
    })

    export class HomeComponent implements OnInit {
      posts: Post[] = [];
      areas: Area[] = [];
      model: any = {};

      constructor(
      private postService: PostService,
      private areaService: AreaService,
      private httpService: HttpService) { }

      ngOnInit() {
            // get posts from secure api end point
            this.postService.getPosts()
                .subscribe(post => {
                    this.posts =  post;
                });
                this.areaService.getAreas()
                .subscribe(area => {
                  this.areas = area;
                });
        }

      upSwipe() {
        // Increase post spread
        this.httpService.POST('/areas/' + this.areas[this.areaService.currentArea].name  +
        '/' + this.posts[0].id + '/spread/1/', JSON.stringify({}))
          .subscribe(
              data => console.log('Burning more wood'));
              this.ngOnInit();
            }

      downSwipe() {
          // Increase post spread
          this.httpService.POST('/areas/' + this.areas[this.areaService.currentArea].name  +
          '/' + this.posts[0].id + '/spread/0/', JSON.stringify({}))
          .subscribe(
              data => console.log('The air seemingly grew colder'));
              this.ngOnInit();
            }

      fun() {
        this.areaService.currentArea = 0;
        this.areaService.currentAreaName = 'fun';
        this.ngOnInit();
      }

      information() {
        this.areaService.currentArea = 1;
        this.areaService.currentAreaName = 'information';
        this.ngOnInit();
      }

      postComment() {
        const text = {
        'text': this.model.comment
    };
        const body = JSON.stringify(text);
        this.httpService.POST('/areas/' + this.areaService.currentAreaName  + '/' + this.posts[0].id + '/', body)
          .subscribe(
              data => console.log('Someone said something in the forest, but did anyone hear it?'));
              this.model.comment = '';
              this.ngOnInit();

      }
    }
我该怎么做

编辑添加的post.service.ts

    import { Injectable } from '@angular/core';
    import { Response } from '@angular/http';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/mergeMap';
    import { AreaService, HttpService} from './index';
    import { Post, Area} from '../_models/index';

    @Injectable()
    export class PostService {
      areas: Area[] = [];
        constructor(
            private areaService: AreaService,
            private httpService: HttpService
          ) { }

        getPosts(): Observable<Post[]> {
            // subscribe until the area is available
            return this.areaService.getAreas().mergeMap(area => {
                // use the area to get the response
                return this.httpService.GET('/areas/' + area[this.areaService.currentArea].name + '/')
                    .map((response: Response) => response.json());
            });
        }
        getFunPosts(): Observable<Post[]> {
          return this.httpService.GET('/areas/fun/own/' )
              .map((response: Response) => response.json());
        }
        getInformationPosts(): Observable<Post[]> {
          return this.httpService.GET('/areas/information/own/' )
              .map((response: Response) => response.json());
        }
    }
从'@angular/core'导入{Injectable};
从'@angular/http'导入{Response};
从“rxjs/Observable”导入{Observable};
导入'rxjs/add/operator/map';
导入'rxjs/add/operator/mergeMap';
从“/index”导入{AreaService,HttpService};
从“../\u models/index”导入{Post,Area}”;
@可注射()
出口邮递服务{
面积:面积[]=[];
建造师(
私人区域服务:区域服务,
私有httpService:httpService
) { }
getPosts():可观察{
//订阅,直到该区域可用
返回此.areaService.getAreas().mergeMap(区域=>{
//使用该区域获取响应
返回此.httpService.GET('/areas/'+area[this.areaService.currentArea].name+'/'))
.map((response:response)=>response.json());
});
}
getFunPosts():可观察{
返回此.httpService.GET(“/areas/fun/own/”)
.map((response:response)=>response.json());
}
getInformationPosts():可观察{
返回此.httpService.GET(“/areas/information/own/”)
.map((response:response)=>response.json());
}
}

如果我理解这一点;当
getAreas()
值更改时,是否要更新
post
数据?为什么不直接运行
postService
而不是重建整个组件?我添加了post.serivce,如何再次运行postService来恢复这些值您可以使用
eventemitter
将值从导航栏组件传递到主组件,并将其放入
onChange()
指令,然后仅重新运行该方法以更新值。或者使用Behavior subject来集中
Posts
数组,并从其他地方订阅它,如果您担心HTML没有得到更新。当
posts
数组中的信息更新时,HTML也将自动更新。你不需要重新创建组件我知道信息会被再次填充,我只需要弄清楚如何从导航栏组件调用更新,作为回报,更新home.comp