在初始加载时使用异步管道时,模板未绑定到observable



我正在使用内容丰富的js SDK在服务中获取数据。SDK提供了一种从promise中检索条目并解析这些条目的方法。由于我想使用可观测,我将承诺作为可观测返回,然后从那里转换。

在我的home组件中,我调用contentfulServiceOnInit,并使用async管道打开模板中的可观察对象。

我的问题:
当主组件加载时,即使服务已成功获取数据,模板也不存在。现在,如果我在页面上与DOM交互(单击、悬停),模板将立即出现。为什么这不只是在页面加载时异步加载?我该怎么解决这个问题?

显示行为的示例.gif。

内容服务.ts

import { Injectable } from '@angular/core';    
import { Observable, Subject } from 'rxjs/Rx';    
import { Service } from '../models/service.model';
import * as contentful from 'contentful';

@Injectable()
export class ContentfulService {
client: any;
services: Service[];
service: Service;    
constructor() {    
this.client = contentful.createClient({
space: SPACE_ID,
accessToken: API_KEY
});
}   

loadServiceEntries(): Observable<Service[]> {
let contentType = 'service';
let selectParams = 'fields';
return this.getEntriesByContentType(contentType, selectParams)
.take(1)          
.map(entries => {
this.services = [];
let parsedEntries = this.parseEntries(entries);
parsedEntries.items.forEach(entry => {
this.service = entry.fields;
this.services.push(this.service);
});
this.sortAlpha(this.services, 'serviceTitle');
return this.services;
})          
.publishReplay(1)
.refCount();
}

parseEntries(data) {
return this.client.parseEntries(data);
}

getEntriesByContentType(contentType, selectParam) {
const subject = new Subject();
this.client.getEntries({
'content_type': contentType,
'select': selectParam
})
.then(
data => {
subject.next(data);
subject.complete();
},
err => {
subject.error(err);
subject.complete();
}
);
return subject.asObservable();
}

sortAlpha(objArray: Array<any>, property: string) {
objArray.sort(function (a, b) {
let textA = a[property].toUpperCase();
let textB = b[property].toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
}

}

home.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { ContentfulService } from '../shared/services/contentful.service';
import { Service } from '../shared/models/service.model';    
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
service: Service;      
services: Service[];
services$: Observable<Service[]>;
constructor(
private contentfulService: ContentfulService,
) {
}    
ngOnInit() {       
this.services$ = this.contentfulService.loadServiceEntries();
this.services$.subscribe(
() => console.log('services loaded'),
console.error
);    
}; 

}

home.component.html

...
<section class="bg-faded">
<div class="container">
<div class="row">
<div class="card-deck">
<div class="col-md-4 mb-4" *ngFor="let service of services$ | async">
<div class="card card-inverse text-center">
<img class="card-img-top img-fluid" [src]="service?.serviceImage?.fields?.file?.url | safeUrl">
<div class="card-block">
<h4 class="card-title">{{service?.serviceTitle}}</h4>
<ul class="list-group list-group-flush">
<li class="list-group-item bg-brand-black"><i class="fa fa-wrench mr-2" aria-hidden="true"></i>Cras justo odio</li>
<li class="list-group-item bg-brand-black"><i class="fa fa-wrench mr-2" aria-hidden="true"></i>Dapibus ac facilisis in</li>
<li class="list-group-item bg-brand-black"><i class="fa fa-wrench mr-2" aria-hidden="true"></i>Vestibulum at eros</li>
</ul>
</div>
<div class="card-footer">
<a href="#" class="btn btn-brand-red">Learn More</a>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
...

听起来Contentful promise正在Angular的区域之外解析。

您可以通过将NgZone注入您的服务来确保可观察的方法在区域内运行:

import { NgZone } from '@angular/core';
constructor(private zone: NgZone) {
this.client = contentful.createClient({
space: SPACE_ID,
accessToken: API_KEY
});
}

在调用受试者的方法时使用注入区域的run进行调用:

getEntriesByContentType(contentType, selectParam) {
const subject = new Subject();
this.client.getEntries({
'content_type': contentType,
'select': selectParam
})
.then(
data => {
this.zone.run(() => {
subject.next(data);
subject.complete();
});
},
err => {
this.zone.run(() => {
subject.error(err);
subject.complete();
});
}
);
return subject.asObservable();
}

最新更新