简体   繁体   English

刷新角度组件

[英]Refreshing Angular component

I have a search component which is a popup on my home page. 我有一个搜索组件,它是我主页上的一个弹出窗口。 After opening the popup and then clicking the search button I call this service below called searchMc. 打开弹出窗口,然后单击搜索按钮后,我将此服务称为下方的searchMc。 This is the search component. 这是搜索组件。

  import {Component, OnInit, EventEmitter, Input, Output} from '@angular/core';
import {McService} from '../../shared/services/mc-service';
import {SearchModel, SearchResultModel, WebSearchModel} from './search-model';
import {Router} from '@angular/router';
import {CommunicationService} from '../../shared/services/communication.service';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.less'],
})
export class SearchComponent implements OnInit {
  @Input() search: boolean;
  @Output() searchChange = new EventEmitter<boolean>();
  storiesAndMedia: boolean;
  stories: boolean;
  media: boolean;
  loader: boolean;
  result: any;

  searchModelData = new SearchModel();
  searchResultResponse = new SearchResultModel();


  constructor(private mcService: McService, private router: Router, private cs: CommunicationService) {
  }

  ngOnInit() {
    this.getSearch();
  }


  getSearch() {
    this.mcService.getSearch()
      .subscribe((response) => {
          this.searchModelData = response;
          this.searchModelData.searchModel = new WebSearchModel();
        },
        (error) => {
          console.log(error);
        });
  }

  selectMedia(index) {
    switch (index) {
      case 1:
        this.searchModelData.searchModel.images = !this.searchModelData.searchModel.images;
        break;
      case 2:
        this.searchModelData.searchModel.video = !this.searchModelData.searchModel.video;
        break;
      case 3:
        this.searchModelData.searchModel.document = !this.searchModelData.searchModel.document;
        break;
      case 4:
        this.searchModelData.searchModel.audio = !this.searchModelData.searchModel.audio;
        break;
    }
  }

  customChecked(custom) {
    custom.marked = !custom.marked;
    const index1 = this.searchModelData.searchModel.customCategoryIds.indexOf(custom);
    if (custom.marked) {
      this.searchModelData.searchModel.customCategoryIds.push(custom.id);
    }
    else {
      this.searchModelData.searchModel.customCategoryIds.splice(index1, 1);
    }
  }

  categoryChecked(category) {
    category.checked = !category.checked;
    const index2 = this.searchModelData.searchModel.mainCategoryIds.indexOf(category);
    if (category.checked) {
      this.searchModelData.searchModel.mainCategoryIds.push(category.id);
    }
    else {
      this.searchModelData.searchModel.mainCategoryIds.splice(index2, 1);
    }
  }

  all() {
    this.searchModelData.searchModel.images = true;
    this.searchModelData.searchModel.video = true;
    this.searchModelData.searchModel.document = true;
    this.searchModelData.searchModel.audio = true;
    this.searchModelData.searchModel.media = !this.searchModelData.searchModel.media;
    this.searchModelData.searchModel.stories = !this.searchModelData.searchModel.stories;
    this.storiesAndMedia = !this.storiesAndMedia;
    this.stories = false;
    this.media = false;
  }

  mediaActive() {
    this.storiesAndMedia = false;
    this.media = !this.media;
    this.stories = false;
    this.searchModelData.searchModel.media = true;
    this.searchModelData.searchModel.stories = false;
  }

  storiesActive() {
    this.searchModelData.searchModel.images = false;
    this.searchModelData.searchModel.video = false;
    this.searchModelData.searchModel.document = false;
    this.searchModelData.searchModel.audio = false;
    this.storiesAndMedia = false;
    this.stories = !this.stories;
    this.media = false;
    this.searchModelData.searchModel.media = false;
    this.searchModelData.searchModel.stories = true;
  }


  brandChecked(brand) {
    brand.checked = !brand.checked;
    const index = this.searchModelData.searchModel.subClientIds.indexOf(brand);
    if (brand.checked) {
      this.searchModelData.searchModel.subClientIds.push(brand.id);
    }
    else {
      this.searchModelData.searchModel.subClientIds.splice(index, 1);
    }
  }

  searchMc() {
    this.loader = true;
    this.closeSearch();
    this.mcService.searchMc(this.searchModelData.searchModel)
      .subscribe((response) => {
          localStorage.clear();
          this.searchResultResponse = response;
          localStorage.setItem('result', JSON.stringify(this.searchResultResponse));
          this.router.navigateByUrl('/results');
          this.loader = false;
        },
        (error) => {
          console.log(error);
        });

  }

  closeSearch() {
    this.searchChange.emit(false);
  }
}

This is the result Component: 这是结果组件:

import {Component, OnInit} from '@angular/core';
import {McService} from '../../shared/services/mc-service';
import {Router} from '@angular/router';
import {CommunicationService} from '../../shared/services/communication.service';

@Component({
  selector: 'app-results',
  templateUrl: './results.component.html',
  styleUrls: ['./results.component.less']
})
export class ResultsComponent implements OnInit {
  result: any;
  autoplay: boolean;
  mediaId: number;
  popup: boolean;
  loader: boolean;
  storyId: number;

  constructor(private mcService: McService, private router: Router, private cs: CommunicationService) {
  }

  ngOnInit(): void {

    if (localStorage.getItem('result') != null) {
      this.result = JSON.parse(localStorage.getItem('result'));
    }
  }

  readMore(id) {
    window.scrollTo(0, 0);
    sessionStorage.setItem('storyId', JSON.stringify(id));
    this.mcService.addViewToNews(id)
      .subscribe((response) => {

        },
        (error2 => {
          console.log(error2);
        }));
    this.router.navigate(['/newsdetail/' + id]);
  }

  openDropdown(id) {
    for (const x of this.result.stories) {
      if (x.storyId === id) {
        x.dropdown = !x.dropdown;
      }
    }
  }


  openMediaPopup(id) {
    this.autoplay = false;
    this.mediaId = id;
    this.popup = true;
    this.mcService.addViewToMedia(id);
  }

  openMediaPopupAutplay(id) {
    this.autoplay = true;
    this.mediaId = id;
    this.popup = true;
    this.mcService.addViewToMedia(id);
  }
}

Then I get redirected to /results . 然后,我被重定向到/results But I have a problem. 但是我有一个问题。 When I am on that same route /results if I click on search popup, then search button which calls the service again, the /results page doesn't refresh the content, because I am on that same route and since I am sending the response of the search through localstorage (I did this because I didn't know any other way) all of the results are stored on localstorage but the results page doesn't get the new content it stays the same. 当我在同一条路线上/results如果我单击搜索弹出窗口,然后单击搜索按钮再次调用该服务,则/results页不会刷新内容,因为我在同一条路线上并且正在发送响应通过localstorage进行搜索(之所以这样做,是因为我不知道其他方法),所有结果都存储在localstorage上,但是结果页面没有得到新内容,它保持不变。 Is there a way to refresh the page every time I click Search button but without using localstorage. 每当我单击“搜索”按钮但不使用localstorage时,是否可以刷新页面。 I've tried some kind of a communication service using Subject it was buggy didn't really work. 我已经尝试过使用Subject进行某种通信服务,但是越野车并没有真正起作用。

Thank you and sorry for my bad english. 谢谢,抱歉我的英语不好。

You have to use a service. 您必须使用一项服务。 Here is an example: 这是一个例子:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';


@Injectable()
export class StorageService {

    private searchItem: BehaviorSubject<string> = new BehaviorSubject('');

    constructor() { }

    getSearchItem(): Observable<string> {
        return this.searchItem.asObservable();
    }

    getSearchItemValue(): string {
        return this.searchItem.getValue();
    }

    setSearchItem(val: string) {
        this.searchItem.next(val);
    }
}

In your ResultComponent subscribe to this service and have your local variable that provides the value updated whenever the value inside the service changes. 在您的ResultComponent中,订阅此服务,并让您的局部变量在服务中的值发生更改时提供更新的值。

Attention! 注意! The value can be whatever you want. 该值可以是您想要的任何值。 It has not strictly to be a string. 它不一定严格是字符串。 This is just for the example. 这仅是示例。

import {StorageService} from 'storage.service.ts';

constructor(
 private storageService: StorageService
){}

ngOnInit(): void {
    // Update with every change
    this.storageService.getSearchTerm().subscribe(term => {
        this.result = term; 
    });
}

And your SearchComponent has to set the value to the StorageSevice after each search instead of putting it to the local storage 并且您的SearchComponent必须在每次搜索后将值设置为StorageSevice,而不是将其放置到本地存储中

import {StorageService} from 'storage.service.ts';

constructor(
 private storageService: StorageService
){}


this.mcService.searchMc(this.searchModelData.searchModel)
  .subscribe((response) => {
      this.searchResultResponse = response;

     this.storageService.setSearchItem(JSON.stringify(this.searchResultResponse));

      this.router.navigateByUrl('/results');
    },
    (error) => {
      console.log(error);
    });

This is another example(!), maybe not the equivalent solution according to the type of your object. 这是另一个示例(!),可能不是根据对象类型的等效解决方案。 It's just supposed to show you that your service can handle every type of object. 它只是向您显示您的服务可以处理每种类型的对象。

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';


@Injectable()
export class StorageService {

    private searchItem: BehaviorSubject< SearchResultResponse > = new BehaviorSubject(any);

    constructor() { }

    getSearchItem(): Observable<any> {
       return this.searchItem.asObservable();
    }

    getSearchItemValue(): SearchResultResponse {
       return this.searchItem.getValue();
    }

    setSearchItem(val: any) {
        this.searchItem.next(val);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM