ngIf仅适用于页面刷新

时间:2019-10-02 18:21:53

标签: angular

我在我的angular应用程序中使用oxford API。我使用了两个不同的端点,第一个是条目,另一个是同义词库。 我只想使用ngIf呈现数据。这适用于条目端点,但不适用于词库。 如果一个单词没有任何同义词和反义词,则不应显示这两个属性,但是在我的应用程序中它不能按预期工作。 例如,如果我搜索``好'',则会显示其数据,包括同义词和反义词;然后如果搜索类似``hanami''的单词,则会从同义词库端点获取错误,指出未找到。但是仍然显示同义词和反义词。以前的结果是“好”这个词。只有在刷新页面后,这两个元素才会被删除。

这是component.ts文件

constructor(public oxford: OxfordService, private route: ActivatedRoute, 
        private router: Router, private toastr: ToastrService, private spinner: NgxSpinnerService) { }

      ngOnInit() {

        this.route.paramMap.subscribe(

          params => {
            //console.log(params);
            this.spinner.show();


            this.wordId = params.get('word_id');

            this.oxford.getDefinition(this.wordId).subscribe(
              data => {
                console.log(data);
                this.o = data;
                this.title = this.o.word;
                this.definitions = this.getProperty(data, "definitions");
                this.examples = this.getProperty(data, "examples");
                this.lexicalCategories = this.getProperty(data, "lexicalCategory");

                this.pronunciations = this.getProperty(data, "pronunciations");
                this.origins = this.getProperty(data, "etymologies");


                this.lexicalCategories = this.removeDuplicateObjects(this.lexicalCategories);
                this.pronunciations = this.removeDuplicateObjects(this.pronunciations);
                this.origins = this.removeDuplicateObjects(this.origins);


                if (this.definitions.length > 0 || this.origins.length > 0 || this.examples.length > 0 || this.pronunciations.length > 0) {
                  this.displayInfo = true;
                }

                this.spinner.hide();

                console.log(this.lexicalCategories, this.pronunciations, this.origins);
              },
              error => {
                console.log(error);
                this.spinner.hide();
                //const message = error.error.error;
                this.toastr.error(`${error.status},${error.error.error}`);
              }

            );

            this.oxford.getSynAndAnt(this.wordId).subscribe(
              data => {
                // console.log(data);
                this.synonyms = this.getProperty(data, "synonyms");
                this.antonyms = this.getProperty(data, "antonyms");

                this.spinner.hide();
                console.log(this.synonyms, this.antonyms);
              },
              error => {
                console.log(error);
                this.spinner.hide();
                this.toastr.error(`${error.status},${error.error.error}`);
              }
            );

          }

        );

      }

这是html文件

 <div class="card" *ngIf="definitions && definitions?.length>0">
    <div class="card-header" id="headingTwo">
      <h2 class="mb-0">
        <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo"
          aria-expanded="false" aria-controls="collapseTwo">
          Definitions
        </button>
      </h2>
    </div>
    <div id="collapseTwo" class="collapse thesaurus" aria-labelledby="headingTwo" data-parent="#accordionExample">
      <div class="card-body">
        <ul class="list-group">
          <li class="list-group-item" *ngFor="let def of definitions">
            {{def}}
          </li>

        </ul>
      </div>
    </div>
  </div>

  <div class="card" *ngIf="examples && examples?.length>0">
    <div class="card-header" id="headingEx">
      <h2 class="mb-0">
        <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseEx"
          aria-expanded="false" aria-controls="collapseEx">
          Examples
        </button>
      </h2>
    </div>
    <div id="collapseEx" class="collapse thesaurus" aria-labelledby="headingEx" data-parent="#accordionExample">
      <div class="card-body">
        <ul class="list-group">
          <li class="list-group-item" *ngFor="let ex of examples">
            {{ex.text}}
          </li>

        </ul>
      </div>
    </div>
  </div>

  <div class="card" *ngIf="synonyms && synonyms?.length>0">
    <div class="card-header" id="headingThree">
      <h2 class="mb-0">
        <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseThree"
          aria-expanded="false" aria-controls="collapseThree">
          Synonyms
        </button>
      </h2>
    </div>
    <div id="collapseThree" class="collapse container thesaurus" aria-labelledby="headingThree"
      data-parent="#accordionExample">
      <div class="card-body row ">

        <p class="col-6 col-md-4 border border-dark text-center" *ngFor="let syn of synonyms">{{syn.text}}</p>
      </div>
    </div>
  </div>

  <div class="card" *ngIf="antonyms && antonyms?.length>0">
    <div class="card-header" id="headingFour">
      <h2 class="mb-0">
        <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseFour"
          aria-expanded="false" aria-controls="collapseFour">
          Antonyms
        </button>
      </h2>
    </div>
    <div id="collapseFour" class="collapse container thesaurus" aria-labelledby="headingFour"
      data-parent="#accordionExample">
      <div class="card-body row">

        <p class="col-6 col-md-4 border border-dark text-center" *ngFor="let ant of antonyms">{{ant.text}}</p>

      </div>
    </div>
  </div>

  <div class="card" *ngIf="pronunciations && pronunciations?.length>0">
    <div class="card-header" id="headingFive">
      <h2 class="mb-0">
        <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseFive"
          aria-expanded="false" aria-controls="collapseFive">
          Pronunciations
        </button>
      </h2>
    </div>
    <div id="collapseFive" class="collapse" aria-labelledby="headingFive" data-parent="#accordionExample">
      <div class="card-body">
        <ul class="list-group">
          <li class="list-group-item" *ngFor="let pron of pronunciations">
            {{pron.phoneticSpelling}}
            <span *ngIf="pron.audioFile">
              <audio #audio [src]="pron.audioFile"></audio>
              <a (click)=play(audio)>
                <i class="fa fa-volume-up" aria-hidden="true"></i>
              </a>
            </span>
          </li>

        </ul>
      </div>
    </div>
  </div>

以下是屏幕截图: with synonyms

error from thesaurus

after page refresh or searching it before all other words

1 个答案:

答案 0 :(得分:0)

您没有以我会使用的方式使用ngOnInit。没有输入,因此实际上不需要生命周期挂钩。另外,您要在另一个内部进行多个订阅。我认为您的依赖关系是启动其他两个订阅的路由器参数。

我的建议是在您的TS中将this.route.paramMap分配为属性(componentState $),并通过

使用异步管道在模板文件中对其进行订阅
<ng-container *ngIf="componentState$ | async as state"></ng-container>

在您的ts中,当时只需断开参数

 componentState$ = this.route.paramMap.pipe(
      map(params => params.get('word_id')), 
      switchMap(wordId => combineLatest([
         this.oxford.getDefinition(wordId), 
         this.oxford.getSynAndAnt(wordId)
      ]).pipe(
            map(([def, synant]) => ({ def, synant }))
         )
      )
   );

您的模板现在可以访问所有以点表示法表示的数据。同样,这意味着您只有一个订阅,并且您无需取消订阅,因为模板异步管道将为您完成这两个任务。无需在您的任务中分配其他道具。