【问题标题】:Calling the service function with button click doesnt update view使用按钮单击调用服务功能不会更新视图
【发布时间】:2018-07-09 18:48:39
【问题描述】:

当我在 ngOnInit() 中调用 this.getLeaderboard(); 时,排行榜仅在页面开始或页面刷新时显示,这是正常的.但我也想从 app.component.ts 获取并在按钮点击时显示排行榜。

当我单击按钮时,流程转到调用 leaderboard.service 的 leaderboard.component,但在 leaderboard.component.html 中没有显示或更新任何内容。如果我 console.log 值在那里但 DOM 没有更新...

我在这里错过了什么?

app.component.html

  <div class="col nopadding">
         <button id="bottomButton2" type="button" class="btn btn-bottom" (click)="getLeaderboard()">
             <img id="bottom2" class="navbar-bottom-pics" src="assets\img\podium.svg">
              <img id="bottom22" class="navbar-bottom-pics hide" src="assets\img\podiumSelected.svg">
         </button>
    </div>

app.component.ts

 import { Component, Injectable } from '@angular/core';
    import { MatchesComponent } from './matches/matches.component';
    import { LeaderboardComponent } from './leaderboard/leaderboard.component';
    import { ClubStatisticsComponent } from './club-statistics/club-statistics.component';

    @Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.css'],
     providers: [LeaderboardComponent,MatchesComponent,ClubStatisticsComponent]
     })

    export class AppComponent{

    constructor(private match_component:MatchesComponent, private 
    leaderboard_component:LeaderboardComponent, private 
    clubstatistics_component:ClubStatisticsComponent){}

    //CALLS FOR BOTTOM NAVBAR
    getLeaderboard(){
      //POSITION SCREEN TO TOP
      window.scrollTo(0, 0);
      //CALL GET LEADERBOARD
      this.leaderboard_component.getLeaderboard();
    }

leaderboard.component.ts

import { Component, OnInit, Injectable} from '@angular/core';
import { leaderboardInstance } from './leaderboardInstance';
import { LeaderboardService } from './leaderboard.service';

@Component({
  selector: 'app-leaderboard',
  templateUrl: './leaderboard.component.html',
  styleUrls: ['./leaderboard.component.css'],
  providers: [LeaderboardService]
})

@Injectable()
export class LeaderboardComponent implements OnInit {

  public leaderboard: leaderboardInstance[];
  public finalLeaderboard: leaderboardInstance[] = new Array();

  constructor(private leaderboard_service: LeaderboardService) { }

  ngOnInit() {

      this.getLeaderboard();

  }

  //GET ACTUAL SERVER JSON RESPONSE AND SUBSCRIBE IT TO array
  getLeaderboard(){
    console.log("leaderboardComponent");
    this.leaderboard_service.getLeaderboard().subscribe(leaderboard =>{ this.leaderboard = this.formatMatchesSingles(leaderboard)});

  }

  formatMatchesSingles(leaderboard){
    console.log("formatMatches");
    let uniqueNames = [];
    let uniqueSurnames = [];
    let matchesPlayed = [];
    let matchesWon = [];

    for(let i = 0; i< leaderboard.length; i++){   

      //FIND ALL UNIQUE NAMES 
      if(uniqueNames.indexOf(leaderboard[i].name1) === -1){
          uniqueNames.push(leaderboard[i].name1);        
      }
      if(uniqueNames.indexOf(leaderboard[i].name2) === -1){
        uniqueNames.push(leaderboard[i].name2);        
      }

      //FIND ALL UNIQUE SURNAMES
      if(uniqueSurnames.indexOf(leaderboard[i].surname1) === -1){
        uniqueSurnames.push(leaderboard[i].surname1);        
      }
      if(uniqueSurnames.indexOf(leaderboard[i].surname2) === -1){
        uniqueSurnames.push(leaderboard[i].surname2);        
      }

    }

    //CALCULATE MATCHES PLAYED
    for(let i=0;i<uniqueNames.length;i++){

      let played = leaderboard.reduce(function(s, o) {
      if (o.name1 === uniqueNames[i] && o.doubles == "0") s++;
      if (o.name2 === uniqueNames[i] && o.doubles == "0") s++;
      return s;
    }, 0);
    matchesPlayed[i]=played;
    }

    //CALCULATE WINS
        for(let i=0;i<uniqueNames.length;i++){

      let wins = leaderboard.reduce(function(s, o) {
      if (o.name1 === uniqueNames[i] && o.sets_team1 > o.sets_team2 && o.doubles == "0") s++;
      else if(o.name2 === uniqueNames[i] && o.sets_team2 > o.sets_team1 && o.doubles == "0") s++;
            return s;
        }, 0);
        matchesWon[i]=wins;
    }

    //CREATE USER OBJECT, ASSIGN ALL VARIABLES AND ADD IT TO ARRAY
    for (let i = 0; i < uniqueNames.length; i++) { 

      let MatchesNo: number = parseFloat(matchesPlayed[i]);
      let MatchesWonNo: number = parseFloat(matchesWon[i]);
      let MatchesLostNo: number = MatchesNo - MatchesWonNo;  //CALCULATE LOSES
      let WinPercentage: number;

      if (MatchesNo > 0 && MatchesWonNo == 0) WinPercentage = 0;
      else WinPercentage = (MatchesWonNo/MatchesNo)*100; //CALCULATE PERCENTAGE
      let newInstance = new leaderboardInstance();
      newInstance.name = uniqueNames[i];
      newInstance.surname = uniqueSurnames[i]
      newInstance.played = matchesPlayed[i];
      newInstance.wins = matchesWon[i];
      newInstance.loses = MatchesLostNo;
      newInstance.percentage = Math.floor(WinPercentage);
      this.finalLeaderboard.push(newInstance);

    }

    //SORT
    this.finalLeaderboard.sort(function(a, b){

      if(a.wins === b.wins){

        if(a.percentage != b.percentage){ //SORT BY PERCENTAGE
          let x = a.percentage, y = b.percentage;  
          return y < x ? -1 : y > x ? 1 : 0;
        }
        else{ //IF ALSO PERCENTAGES ARE THE SAME THEN SORT BY PLAYED MATCHES
          let x = a.played, y = b.played;
          return y < x ? -1 : y > x ? 1 : 0;
        }
      }
      return b.wins - a.wins //DEFAULT SORT BY WINS
    });


    return this.finalLeaderboard;
  }

}

leaderboard.service.ts

import { Injectable } from '@angular/core';
import { leaderboardInstance } from './leaderboardInstance';
import { Observable, Subject } from 'rxjs';
import { HttpClient, HttpParams } from '@angular/common/http';
import {SHA256} from 'crypto-js';

@Injectable()
export class LeaderboardService {

constructor(private http: HttpClient) { }

getLeaderboard(): Observable<leaderboardInstance[]>  {
console.log("leaderboardservice");
let url="ourAPIurl";

var salt = "1234"
var hash1 = SHA256(salt+"lalalala");

localStorage.setItem('methodName', 'GetMatchesOfGroup');
localStorage.setItem('userId', '2');
localStorage.setItem('token', String(hash1));
localStorage.setItem('id_group', '7');
localStorage.setItem('password', String(hash1));
localStorage.setItem('madCheck', 'bc8fcafb0829db3744d0aad45ebda03882d25367291de3883a8c7f75a9c45fb5');

const params = new HttpParams()
.set('methodName', localStorage.getItem('methodName'))
.set('userId', localStorage.getItem('userId'))
.set('token', localStorage.getItem('token'))
.set('id_group', localStorage.getItem('id_group'))
.set('password', localStorage.getItem('password'))
.set('madCheck', localStorage.getItem('madCheck'));

return this.http.post<leaderboardInstance[]>(url, params, {responseType: 'json'});

}
}

leaderboard.component.html

    <tbody>
    <tr *ngFor="let leaderboardInstance of leaderboard; index as i">
      <td width=25><div id="rank1">{{i+1}}</div></td>
      <td><a class="name-table">{{leaderboardInstance.name | uppercase}} {{leaderboardInstance.surname | uppercase | slice:0:1}}<span>.</span></a></td>
      <td class="played">{{leaderboardInstance.played}}</td>
      <td class="won">{{leaderboardInstance.wins}}</td>
      <td class="loses">{{leaderboardInstance.loses}}</td>
      <td class ="percentage" class="center">{{leaderboardInstance.percentage}}<span>%</span></td>
    </tr>
  </tbody>
  </table>
</div>

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    我认为您想通过 ViewChild 注释获取组件引用,然后像这样从构造函数中删除它们:

    export class AppComponent{
        @ViewChild(MatchesComponent)
        private match_component: MatchesComponent;
    
        @ViewChild(LeaderboardComponent)
        private leaderboard_component: LeaderboardComponent;
    
        @ViewChild(ClubStatisticsComponent)
        private clubstatistics_component: ClubStatisticsComponent;
    
        constructor(){}
    

    并将它们从您的AppComponent 中的providers 数组中删除。您通常只希望将服务注入这样的组件中。

    【讨论】:

    • 太棒了,如果你也能接受这个作为答案,那就太好了! :)
    • 我接受了,但它说“那些声望低于 15 的人的投票会被记录下来,但不会改变公开显示的帖子得分。”...
    【解决方案2】:

    也许leaderboard-array 只是在更新它的条目,而不是列表本身?如果您从同一个列表中添加或删除元素,Angular 不会检测到更改。您可以使用此处提供的答案:https://stackoverflow.com/a/42962723/1471485,也可以在获得排行榜时重新创建列表:

    this.leaderboard = [].concat(this.formatMatchesSingles(leaderboard));
    

    使用[].concat 创建一个新实例,Angular 会检测到更改。

    【讨论】:

    • 完全不像,他在这里设置新对象this.leaderboard = this.formatMatchesSingles(leaderboard)
    • 是的,你是对的,它看起来不是那样的。但是,我不知道formatMatchesSingles() 的内容,但可能是 OP 正在编辑现有列表并返回它。类似于这个 stackBlitz 的东西:stackblitz.com/edit/random-list-check
    • 啊,我现在明白你的意思了——那会很无聊——我猜是不是很搞笑?
    • 那确实很奇怪:P
    • formatMatchesSingles() 是我对排行榜进行排序然后返回排序的位置。那么在从服务器获取数组后对它进行排序的非搞笑方式是什么?我添加了 formatMatchesSingles() 的缺失代码
    猜你喜欢
    • 2021-03-27
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    相关资源
    最近更新 更多