从服务调用时,组件不会在第一个视图上加载

时间:2017-12-13 21:08:31

标签: angular angular-services angular-components

我们正在实现从服务加载的第一个组件,虽然在我们第一次加载页面时数据永远不可见,但它仍然有效。完全刷新页面后,我们需要查看此组件(加载空白),导航到另一个组件,当我们返回数据时,加载正常。谁能解释我们做错了什么?

这是组件

import { Component, OnInit } from '@angular/core';
import { StbBaseComponent } from './StbBaseComponent';
import { IRegion } from './region.component';
import { RegionService } from '../services/region.service';

@Component({
    selector: 'region-list',
    templateUrl: './regionlist.component.html',
    styleUrls: ['./regionlist.component.less']
})
export class RegionListComponent extends StbBaseComponent implements OnInit {
    public regions: IRegion[];
    public selectedRegion: IRegion;

    constructor(private regionService: RegionService) {
        super();
    }

    ngOnInit() {
        this.getRegions();
    }

    onSelect(region: IRegion): void {
        this.selectedRegion = region;
    }

    getRegions(): void {
        this.regionService.getRegions().subscribe(regions => this.regions = regions);
    }
}

这是服务实现

import { Injectable, Inject } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

import { Http } from '@angular/http';
import { IRegion } from '../components/region.component';

@Injectable()
export class RegionService {
    private baseServiceUrl: string;
    private fetchedRegions: IRegion[];

    constructor(private http: Http,
        @Inject('BASE_URL') baseUrl: string)
    { this.baseServiceUrl = baseUrl }

    getRegions(): Observable<IRegion[]> {
        var url = this.baseServiceUrl + 'api/realm/regions';

        this.http.get(url).subscribe(result => {
            this.fetchedRegions = result.json() as IRegion[];
            console.log('regions called. count:' + this.fetchedRegions.length);
        }, error => {
            console.error(error)
        });

        return of(this.fetchedRegions);
    }
}

我们用来访问该组件的链接是

<li [routerLinkActive]="['link-active']">
    <a [routerLink]="['/regions']">
        Regions
    </a>
</li>

以下是NgModule配置

@NgModule({
    declarations: [
        AppComponent,
        NavMenuComponent,
        HomeComponent,
        RegionListComponent
    ],
    imports: [
        CommonModule,
        HttpModule,
        FormsModule,
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'regions', component: RegionListComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ],
    providers: [RegionService]
})

2 个答案:

答案 0 :(得分:1)

我认为这里发生的事情是 1)您正在订阅服务调用,这是异步操作并返回this.fetchedRegions,这将是空白的。因此,没有数据显示何时加载页面,因为根本没有延迟 2)接下来,当您导航到另一条路线并返回时,this.fetchedRegions将被解析,因此您可以看到数据。

用map替换服务中的subscribe,不要返回this.fetchedRegions。组件中的订阅应该负责解析http调用

答案 1 :(得分:1)

RRForUI已经解释了你的代码有什么问题,

您需要进行以下更改

RegionService:

getRegions(): Observable<IRegion[]> {
    var url = this.baseServiceUrl + 'api/realm/regions';
    return this.http.get(url).map((res: Response) => res.json());
}

在你的组件中,

getRegions(): void {
    this.regionService.getRegions().subscribe(regions => this.regions = regions);
}

PS :总是更喜欢使用HttpClient而不是Http,这将被弃用。

使用HttpClient您的代码变得更加简单,

return this.http.get<IRegion[]>(url);