簡體   English   中英

刷新角度組件

[英]Refreshing Angular component

我有一個搜索組件,它是我主頁上的一個彈出窗口。 打開彈出窗口,然后單擊搜索按鈕后,我將此服務稱為下方的searchMc。 這是搜索組件。

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

這是結果組件:

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

然后,我被重定向到/results 但是我有一個問題。 當我在同一條路線上/results如果我單擊搜索彈出窗口,然后單擊搜索按鈕再次調用該服務,則/results頁不會刷新內容,因為我在同一條路線上並且正在發送響應通過localstorage進行搜索(之所以這樣做,是因為我不知道其他方法),所有結果都存儲在localstorage上,但是結果頁面沒有得到新內容,它保持不變。 每當我單擊“搜索”按鈕但不使用localstorage時,是否可以刷新頁面。 我已經嘗試過使用Subject進行某種通信服務,但是越野車並沒有真正起作用。

謝謝,抱歉我的英語不好。

您必須使用一項服務。 這是一個例子:

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

在您的ResultComponent中,訂閱此服務,並讓您的局部變量在服務中的值發生更改時提供更新的值。

注意! 該值可以是您想要的任何值。 它不一定嚴格是字符串。 這僅是示例。

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

constructor(
 private storageService: StorageService
){}

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

並且您的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);
    });

這是另一個示例(!),可能不是根據對象類型的等效解決方案。 它只是向您顯示您的服務可以處理每種類型的對象。

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