【问题标题】:Angular 7: Service not updating the page dynamically, Its getting updated after reloading the pageAngular 7:服务未动态更新页面,重新加载页面后更新
【发布时间】:2020-05-06 23:10:05
【问题描述】:

我在angular 7 工作,我必须执行简单的任务,有一个组件teacher-details 以表格格式显示注册教师列表(使用节点 js 从数据库中获取)并在新表格时更新表格添加了教师记录,我还有一个teacher.service.ts,其中包含教师数组并包含方法getTeacher()addTeacher(),因此教师组件使用此服务来显示记录。

我的问题是当我输入教师的新记录时,它没有更新到 UI/页面,但是当我重新加载它时它会更新,但是我想在输入记录后立即动态更新页面。

teacher-details.component.ts

@Component({
  selector: 'app-teacher-details',
  templateUrl: './teacher-details.component.html',
  styleUrls: ['./teacher-details.component.css']
})
export class TeacherDetailsComponent implements OnInit {

  private teachers: Teacher[] = []
  constructor(private teacherServ: TeachersService, private auth: AuthService) {
   }

  ngOnInit() {

    this.auth.getTeacherRecords().subscribe(
      res => this.teachers = res.message,
      err => console.log(err)
    ),



    this.teachers = this.teacherServ.getTeachers();
  }

}

teacher.service.ts

@Injectable()
export class TeachersService {
teacherChanged = new EventEmitter<Teacher[]>();
private teachers: Teacher[] = [];

  constructor(private auth: AuthService) {}

  getTeachers() {
    return this.teachers;
  }

  addTeachers(teacher: any) {
    this.auth.addTeacher(teacher)
    .subscribe(
      res => console.log(res),
      err => console.log(err)
    );
    this.teachers.push(teacher);
  }
}

我还分享了我的身份验证服务,该服务从数据库中获取详细信息。

@Injectable()
export class AuthService {

  private addTeacherUrl = "http://localhost:3000/api/addTeacher"
  private getTeacherRecordsUrl = "http://localhost:3000/api/getTeacherRecords"

  addTeacher(teacherRecord: any) {
    console.log("Inside addTEacher servvice")
    console.log(teacherRecord)
    return this.http.post<any>(this.addTeacherUrl, teacherRecord)
  }

  getTeacherRecords() {
    return this.http.get<any>(this.getTeacherRecordsUrl, {
     observe: "body" 
    })
  }
}

teacher-details.component.html

<div class="card">
  <div class="card-header border-0">
    <div class="row align-items-center">
      <div class="col">
        <h3 class="mb-0">Teacher Details</h3>
      </div>
    </div>
  </div>
  <div class="table-responsive">
    <!-- Projects table -->
    <table class="table align-items-center table-flush">
      <thead class="thead-light">
        <tr>
          <th scope="col">Teacher Name</th>
          <th scope="col">Teacher subject</th>
          <th scope="col">Teacher branch</th>
          <th scope="col">Teacher Semester</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let teachers of teachers">
          <th scope="row">
            {{teachers.fullName}}
          </th>
          <td>
            {{teachers.subject}}
          </td>
          <td>
            {{teachers.branch}}
          </td>
          <td>
            {{teachers.semester}}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

我很困惑我该怎么办,请在这里帮帮我。

更新:-

我根据建议做了如下修改:

auth.service.ts

@Injectable()
export class AuthService {

  private addTeacherUrl = "http://localhost:3000/api/addTeacher"
  private getTeacherRecordsUrl = "http://localhost:3000/api/getTeacherRecords"

   subject = new Subject<Teacher[]>();
   teachers: Teacher[] 
  constructor(private http: HttpClient) { }

  addTeacher(teacherRecord: any) {

    console.log("Inside addTEacher servvice")
    console.log(teacherRecord)
    this.teachers.push(teacherRecord)
    this.subject.next(this.teachers)
    return this.http.post<any>(this.addTeacherUrl, teacherRecord)
  }

  getTeacherRecords() {
    return this.http.get<any>(this.getTeacherRecordsUrl, {
     observe: "body" 
    })
  }
}

teacher-details.component.ts

@Component({
  selector: 'app-teacher-details',
  templateUrl: './teacher-details.component.html',
  styleUrls: ['./teacher-details.component.css']
})
export class TeacherDetailsComponent implements OnInit {

   teachers: Teacher[];
  constructor(private teacherServ: TeachersService, private auth: AuthService) {
   }

  ngOnInit() {
    this.auth.getTeacherRecords().subscribe(
      res => this.teachers = res.message,
      err => console.log(err)
    );


    this.auth.subject.subscribe(
      res => console.log(res),
      err => console.log(err)
    )
  }

}

重新加载页面后仍会更新数据

谢谢。

【问题讨论】:

    标签: angular


    【解决方案1】:

    您的服务中的getTeachers() 方法是同步的,只有在调用时才会返回值。

    您可能需要一个Subject,只要您告诉它,它就会发出值。 我相信你的服务是这样的:

    import { Subject } from 'rxjs';
    
    const subject = new Subject<Teacher[]>();
    
    addTeacher(teacherRecord: any) {
        console.log("Inside addTEacher servvice")
        console.log(teacherRecord)
        //HERE YOU ADD THIS
        this.teachers.add(teacherRecord);
        this.subject.next(this.teachers);
    
        return this.http.post<any>(this.addTeacherUrl, teacherRecord)
    }
    

    在你的 ts 文件中你像这样初始化:

    ngOnInit() {
    
        this.auth.getTeacherRecords().subscribe(
          res => this.teachers = res.message,
          err => console.log(err)
        ),
    
        this.auth.subject.subscribe(
          res => this.teachers = res.message,
          err => console.log(err)
        ),
      }
    

    另外,请记住取消订阅 OnDestroy 以避免内存泄漏。

    【讨论】:

    • Sen Alexandru 感谢您的回复,它会更新值,但会删除页面中已经存在的旧数据。
    • @AyushVerma 我已经更新了我的答案。请检查更新的addTeacher() 方法
    • 我确实工作了,我更新了我的新代码,请检查一下。请让我知道我做错了什么
    • @AyushVerma 我相信错误是由teachers 变量未初始化这一事实产生的。我会用teachers: Teacher[] = [] 改变那行
    • @AyushVerma 是的,但是有很多问题。首先,该示例无法正常工作,正如您可能看到的那样,当您尝试在 stackblitz 上运行它时会出现错误。 url 应该在 environment.ts 文件中,而不是在身份验证服务中。所有与教师相关的逻辑都应该在教师服务中,而不是在身份验证等中。所以,我的建议是尝试清理和组织代码。放置一些断点或 console.log 以查看会发生什么
    【解决方案2】:

    您订阅了onInit() 中的getTeacherRecords()

    此方法返回一个 observable,当您在页面上执行某些操作时,该 observable 不会更新,因为没有发送新的 HTTP 请求。

    问题在于您使用了一个不发出其他值的可观察对象。 如我所见,您在教师服务中使用EventEmitter。 你应该像这样在你的组件中订阅它:

    ngOnInit() {
        this.teachers = this.teacherServ.teacherChanged.subscribe(
            teachers => this.teachers = teachers
        );
      }
    

    注意您应该在ngOnDestroy 中使用unsubscribe - 这是最佳做法。

    添加后不要忘记发出教师:

    addTeachers(teacher: any) {
        this.auth.addTeacher(teacher)
        .subscribe(
          res => console.log(res),
          err => console.log(err)
        );
        this.teachers.push(teacher);
        // note that line
        this.teacherChanged.emit(this.teachers);
      }
    

    这应该可行,希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 2022-12-22
      • 1970-01-01
      • 2021-07-19
      • 2017-04-19
      • 2011-04-08
      • 2021-01-23
      相关资源
      最近更新 更多