01/10/2018, 15:45

Angular render component trước khi data về

Chuyện là em có đang làm thử 1 web e-learning bằng angular . . .

Đến phần hiển thị các khóa học thì gặp trục trặc . . .

Mấy ngày trước data các khóa học để ở local thì nó hiển thị . . .

Em có thử cho get data khóa học từ firebase thì nó không hiển thị ngay . . .

Phải chuyển qua 1 component khác rồi quay trở lại nó mới hiển thị . . .

Theo em hiểu thì data get từ firebase về có độ trễ . . .

Do đó data chưa về tới nơi thì angular nó render ra và bị trống . . .

Hiện tại em không chắc mình có sai chỗ nào không . . .

Và chưa nghĩ ra cách giải quyết . . .

Em có deploy lên firebase thử . . .

Mọi người coi qua rồi giúp em . . .

https://kha-e-learning.firebaseapp.com/

Kịch bản hiện tại là vào web - không hiện data - chuyển qua contact - chuyển lại về home thì data lại hiển thị . . .

https://gitlab.com/nkha0103/e-Learning-Project/blob/master/src/app/providers/course.service.ts - Đây là services em dùng để get data khóa học từ firebase

https://gitlab.com/nkha0103/e-Learning-Project/blob/master/src/app/main-content/intro/intro.component.ts - Đây là component dùng services trên để lấy data đó

Nguyen Ca viết 17:57 ngày 01/10/2018

vậy thì đợi data trả về rồi mới binding data vào.
Dùng promise cũng được

MDN Web Docs

Promise

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

Kha Nguyễn viết 17:50 ngày 01/10/2018

Cám ơn anh cơ mà thực sự thì em chưa hiểu về promise lắm . . .

Trong trường hợp của em . . .

Em đứng từ component gọi tới hàm get data ở services . . .

Vậy dùng promise ở services hay tại component ta . . .

Nguyen Ca viết 17:49 ngày 01/10/2018

promise ở service chứ
dạng vậy nè

static receiveFeed(id) {
    const path = id
    console.log(id)
    return new Promise((resovle, reject) => {
      //httpGet(path,{})
      //.then((res) => {
      console.log(reject)
      const feeds = require(path)
      const feed = _.map(feeds.data, (item) => {
        return this.populateFeed(item)
      })
      resovle(feed)
      //})
      //.catch((err) => {
      //  reject(err)
      //})
    })
  }

sau đó gọi như vầy:

Feed.receiveFeed(id).then((feedData) => {
        //populate data
      })
Kha Nguyễn viết 17:49 ngày 01/10/2018

Cám ơn anh vì mất chút thời gian . . .

Cơ mà hơi khó để trình bày chút thì đoạn code component của em nó như này . . .

  ngOnInit() {

    // Get course //
    this._courseService.courses.subscribe(newcourse => {
      this.courses = newcourse;
      console.log(this.courses);
    });
    this._courseService.getCourses();

    // Get front end courses //
    this.frontends = this.filterCourse('front-end');
    console.log('front-end courses after filter');
    console.log(this.frontends);

    // Get back end courses //
    this.backends = this.filterCourse('back-end');
    console.log('back-end courses after filter');
    console.log(this.backends);

  }

Em debug thì hiểu là data lúc get ở chỗ “this._courseService.getCourses();” nó chưa kịp next . . .

Thì đã chạy tiếp hàm phía dưới . . .

Thì phải chăng mình nên promise ở đây không ta . . .

Nguyen Ca viết 17:46 ngày 01/10/2018

this._courseService.getCourses()

nếu bên kia tra về promise thì nó nó phải như thế này

this._courseService.getCourses().then(rs){
// Get front end courses //
    this.frontends = this.filterCourse('front-end');
    console.log('front-end courses after filter');
    console.log(this.frontends);

    // Get back end courses //
    this.backends = this.filterCourse('back-end');
    console.log('back-end courses after filter');
    console.log(this.backends);
}
Kha Nguyễn viết 17:58 ngày 01/10/2018

Ô cám ơn anh . . .

Nhìn có vẻ hiểu rồi . . .

Để chiều làm về thử phát . . .

Dark.Hades viết 17:47 ngày 01/10/2018

Hoặc bạn có thể dùng async await function.

Kha Nguyễn viết 17:54 ngày 01/10/2018

Cái này hình như là cải tiến của promise nè phải không ta . . .

Để em tham khảo thử . . .

Thuc Nguyen Tan viết 17:55 ngày 01/10/2018

Tặng bạn đoạn code này

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.6.0/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/2.0.1/angularfire.min.js"></script>
<script>
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);
</script>
<script>
    var app = angular.module('myApp', ["firebase"]);
    app.controller('myCtrl', function($scope,$firebaseArray) {
		$scope.msg1="hello world";
		var ref = firebase.database().ref().child("msg");
		$scope.msg=$firebaseArray(ref);
    });
</script>
<div ng-app="myApp" ng-controller="myCtrl">
    $scope.msg :{{msg1}}<br>
    <div ng-repeat="x in msg">
    	$id : {{x.$id}}<br>
    	nd : {{x.nd}}<br>
    	date : {{x.date}}<br><br>
    </div>
</div>

Cái này trong tàng kinh các của mình, bảo đảm chạy, chịu khó áp dụng vào trường hợp bạn.

Hay bạn vào trang
vibigaba.esy.es
có đoạn code tương tự thế

Kha Nguyễn viết 17:55 ngày 01/10/2018

Cám ơn bác . . .

Em mới chỉ get data thử thôi chứ chưa tới đây nữa hehe . . .

kiencon viết 17:50 ngày 01/10/2018

khuyên bạn 1 câu, lên youtube học mấy khóa angular mấy trung tâm post lên, mày mò xào nấu sẽ hiểu đc khoảng 20 30% về nó, sau đó vô angular.io để học cho đàng hoàng, có tutorial và tài liệu giải thích khá rõ ràng. Chứ học kiểu này bug quài dễ nản ^^

Kha Nguyễn viết 17:53 ngày 01/10/2018

Em cũng là học qua rồi bắt tay vào làm thử gặp bug thì đi hỏi mà bác . . .

Chưa coi qua sao biết route riếc gì dc bác . . . ^^

Bài liên quan
0