Angular4延迟模板加载,直到收到API响应

时间:2017-10-25 00:04:46

标签: angular angular-services subscription

我需要在加载状态下创建模板,直到收到API响应。

模板

<p>project: {{event.event_title}}
</p>

ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import {ServicesApiCustomerEventService} from "../../services/services-api/services-api-customer/services-api-customer-event.service";
import { Subscription } from 'rxjs/Subscription';

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

  id: any;
  event: any;
  subscription: Subscription;

  constructor(private route: ActivatedRoute,private eventService: ServicesApiCustomerEventService) {
    this.subscription = this.route.params.subscribe(params => {
      this.id = params['id'];
   });

   this.eventService.getEventById(this.id)
   .subscribe(
     data => {
       const a=data.json();
       this.event=a;
     }
   )
  }

  ngOnInit() {

  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

服务

import { Injectable } from '@angular/core';
import {Http,Headers} from "@angular/http";
import 'rxjs/add/operator/map';
import {environment} from "../../../../environments/environment";

@Injectable()
export class ServicesApiCustomerEventService {
    url= `${environment.apiUrl}`;

    constructor(private http: Http) { }

    getEventById(id){
      let headers = new Headers();
      let currentUser = JSON.parse(localStorage.getItem('currentUser'));
      headers.append('Authorization',currentUser.token);
      headers.append("Content-Type", 'application/json')
      return this.http.post(this.url+'/customer/get_event_by_id',{"event_id": id}, {headers: headers})
    }  
}

错误

ERROR TypeError: Cannot read property 'event.event_title' of undefined
    at Object.eval [as updateRenderer] (CustomerEventComponent.html:1)
    at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:13113)
    at checkAndUpdateView (core.es5.js:12260)
    at callViewAction (core.es5.js:12620)
    at execComponentViewsAction (core.es5.js:12552)
    at checkAndUpdateView (core.es5.js:12261)
    at callViewAction (core.es5.js:12620)
    at execEmbeddedViewsAction (core.es5.js:12578)
    at checkAndUpdateView (core.es5.js:12256)
    at callViewAction (core.es5.js:12620)

问题是,因为接收API响应需要一些时间,因此我在加载模板时会收到未定义的错误。谁可以帮我这个事?这样做的最佳做法是什么?

1 个答案:

答案 0 :(得分:0)

您需要在组件路径中添加解析器。 https://angular.io/api/router/Resolve 在您的路线中,它应该看起来像

2018-05-20 13:32:21.393 xcodebuild[1348:5913] Error Domain=IDETestOperationsObserverErrorDomain Code=4 "Test operation was canceled. If you believe this error represents a bug, please attach the log file at /Users/travis/Library/Developer/Xcode/DerivedData/CF_Apps-eihscxvvnylkkecahehxquvcotoo/Logs/Test/2B963612-D4B6-4CE6-BD58-FC9C49FFAE11/Session-CF Apps Tests-2018-05-20_133203-xth6Px.log" UserInfo={NSLocalizedDescription=Test operation was canceled. If you believe this error represents a bug, please attach the log file at /Users/travis/Library/Developer/Xcode/DerivedData/CF_Apps-eihscxvvnylkkecahehxquvcotoo/Logs/Test/2B963612-D4B6-4CE6-BD58-FC9C49FFAE11/Session-CF Apps Tests-2018-05-20_133203-xth6Px.log}
2018-05-20 13:32:21.394 xcodebuild[1348:7053] Connection peer refused channel request for "dtxproxy:XCTestManager_IDEInterface:XCTestManager_DaemonConnectionInterface"; channel canceled <DTXChannel: 0x7fb70286f820>
Testing failed:
    '...' is not a postfix unary operator
    'count' is unavailable: there is no universally good answer, see the documentation comment for discussion
    Cannot convert value of type 'Int' to expected argument type 'IntMax' (aka 'Int64')
    Cannot convert value of type 'Int8' to expected argument type 'IntMax' (aka 'Int64')
    Cannot convert value of type 'Int16' to expected argument type 'IntMax' (aka 'Int64')
    Cannot convert value of type 'Int32' to expected argument type 'IntMax' (aka 'Int64')
    Cannot convert value of type 'UInt' to expected argument type 'UIntMax' (aka 'UInt64')
    Cannot convert value of type 'UInt8' to expected argument type 'UIntMax' (aka 'UInt64')
    Cannot convert value of type 'UInt16' to expected argument type 'UIntMax' (aka 'UInt64')
    Cannot convert value of type 'UInt32' to expected argument type 'UIntMax' (aka 'UInt64')
** TEST FAILED **
The following build commands failed:
    CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler
    CompileSwift normal x86_64 /Users/travis/build/osis/cf-apps-ios/Pods/ObjectMapper/Sources/HexColorTransform.swift
    CompileSwift normal x86_64 /Users/travis/build/osis/cf-apps-ios/Pods/ObjectMapper/Sources/IntegerOperators.swift
(3 failures)
The command "xcodebuild -workspace CF\ Apps.xcworkspace -scheme CF\ Apps -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone SE' build-for-testing test" exited with 65.
Done. Your build exited with 1.
/Users/travis/.travis/job_stages: line 166: shell_session_update: command not found

在您的解析器服务中,例如:

{ path: PATH.EVENTS_ID, component: CustomerEventComponent, resolve: {event: EventResolverService} }

在您的组件中:而不是订阅,只需从请求中获取数据

  resolve(route: ActivatedRouteSnapshot): Observable<IEvent> {
    return this.eventService.getEventById(route.params['id']).map((event: IEvent) => event);
  }