等待POST完成并从服务返回状态

时间:2017-11-06 20:52:05

标签: angular

我正在使用public postComment(comment: string) { this._http.post(this.serviceUrl, { comment }) .subscribe( response => { console.log(response); }); } 中的新post。我的组件和服务设置如下:

component.ts

200

service.ts

post

declare var google: any; @Input() origin:any; @Input() destination:any; @Input() waypoints:any; subtitle:string; constructor( private costumer:ConsumerService, private _elem: ElementRef, private _mapsWrapper: GoogleMapsAPIWrapper, private loader:MapsAPILoader ) { this.subtitle = "This is some text within a card block." } lat: number = 51.678418; lng: number = 7.809007; ngOnInit(){ this._mapsWrapper.getNativeMap().then(response => { var directionsService = new google.maps.DirectionsService; var directionsDisplay = new google.maps.DirectionsRenderer; var map = new google.maps.Map(document.getElementById('map'), { zoom: 7, center: {lat: 41.85, lng: -87.65} }); console.log(map); directionsDisplay.setMap(map); directionsDisplay.setOptions({ polylineOptions: { strokeWeight: 8, strokeOpacity: 0.7, strokeColor: '#00468c' } }); directionsService.route({ origin: { lat: '51.673858', lng:'7.815982' }, destination: {lat: '51.723858', lng: '7.895982'}, optimizeWaypoints: true, travelMode: 'DRIVING' }, function(response, status) { if (status === 'OK') { directionsDisplay.setDirections(response); } else { window.alert('Directions request failed due to ' + status); } }); }); } 不会返回任何内容。如果成功则只返回autoreload,如果不成功则返回错误状态。

如何从我的组件中等待服务中A = [[0.0, 10.0], [1.0, 10.0], [2.0, 10.0], [3.0, 10.0], [4.0, 10.0], [5.0, 10.0], [6.0, 10.0]] B = [[0.0, 2.0], [5.0, 6.0]] Bvals = [item for sublist in B for item in sublist] print(Bvals) newA = [x if x[0] in Bvals else [x[0], 0.0] for x in A] print(newA) Outputs: [0.0, 2.0, 5.0, 6.0] [[0.0, 10.0], [1.0, 0.0], [2.0, 10.0], [3.0, 0.0], [4.0, 0.0], [5.0, 10.0], [6.0, 10.0]] 来电的HTTP响应状态?

1 个答案:

答案 0 :(得分:2)

这不是人们通常的服务方式。返回 Observable from the service并订阅该组件:

组件

public saveComment() {
    this._service.postComment(this.comment)
        .subscribe(
            success => this.getComments(),  // See new method below, just ignore `success`.
            error => handleError(error)
        );
}

public getComments() {
    this._service.getComments()
        .subscribe(
             comments => this.comments = comments,
             error => this.handleError(error),
             () => doSomethingElseOnceComplete(),
        );
}

服务

public postComment(comment: string) {
    return this._http.post(this.serviceUrl, { comment });
}

public getComments(comment: string) {
    return this._http.get(this.serviceUrl);
}

请参阅我在getComments()上的添加内容:您可能希望做同样的事情并将其包装在辅助函数中,而不是使其异步。这是使用Observable s的重点:你传递它们并对它们采取行动,非常像Promise

会发生什么?

next回调(此处说明性地分配给success)将使用REST返回的值调用,这没什么,但我们不在乎,所以你可以忽略它以及事实是null

您可以使用next回调仅在请求成功时调用以触发以下相关操作,刷新注释的事实。

您可以处理评论未能在该错误处理程序中发布的错误。

另请注意,从角度4.3开始,HttpClientModule将替换旧的HttpModule,最终将弃用。