我正在服务中进行 HTTP 调用并将返回数据分配给服务变量。现在,当我尝试访问组件中的服务变量时,它在控制台中记录为未定义。但是,当我将日志代码放入服务本身时它会被记录,但在组件中它不起作用。
下面是我的代码供参考:
英雄服务
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Hero } from './hero';
@Injectable()
export class HeroService {
heroes: Hero[];
hero: Hero;
gbl: Hero[];
private heroesUrl = 'SERVICE URL';
constructor (private http: Http) {}
getHeroes(): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json()['data'];
this.gbl = body;
return body || { };
} …Run Code Online (Sandbox Code Playgroud) typescript angular2-routing angular2-services angular2-observables angular
我刚刚在使用 AngularFire2 Observables 时遇到了一个奇怪的问题,请查看此代码并告诉我您是否对正在发生的事情有所了解:
async save(){
const client = await this.getClient(this.id);
console.log(client); // ZoneAwarePromise blah blah
}
getClient(clientId) {
return this.db.object('clients/' + clientId)
.valueChanges()
.toPromise()
.then((client: any) => {key: clientId, name: client.name});
}
Run Code Online (Sandbox Code Playgroud)
所以这段代码不起作用,但如果我像下一个代码一样这样做,它将起作用:
async save(){
const client = await this.getClient(this.id);
console.log(client); // {key: 'blah', name: 'fooblah'}
}
getClient(clientId) {
return new Promise((resolve, reject) => {
this.db.object('clients/' + clientId)
.valueChanges()
.subscribe((client: any) => resolve({key: clientId, name: client.name}));
}
Run Code Online (Sandbox Code Playgroud)
那么如何在 .toPromise() 方法不起作用的情况下创建承诺并解析 Observable 数据有效呢?
这是正常行为吗?难道我做错了什么 ?让我知道 :-)
我想在可观察对象内部调用http请求,这使得从数据库进行选择操作。我做了两个服务,DbService和BackendService。
BackendService发出http发布请求并返回响应数据。在我的设计中,BackendService应该订阅DbService来获取URL,之后发出http发布请求,然后返回响应数据。
BackendService可以从DbService获取url,并尝试发出http请求,但不能。响应数据为(Json格式)
{"_isScalar":false,"source":{"_isScalar":false},"operator":{}}
Run Code Online (Sandbox Code Playgroud)
我不明白这里发生了什么。我的服务和AppComponent文件在下面。
有BackendService
import { Injectable } from "@angular/core";
import { getString, setString } from "application-settings";
import { Headers, Http, Response, RequestOptions } from "@angular/http";
import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/of';
import "rxjs/add/operator/do";
import "rxjs/add/operator/map";
import "rxjs/add/observable/throw";
import "rxjs/add/operator/catch";
import { DbService } from "./db.service";
@Injectable()
export class BackendService {
static BaseUrl= "http://blabla.com"
constructor(public http: Http, private db: DbService) {
}
sendPost(key: string, requestObj: Object):Observable<any>{
console.log("sendPost: ");
return new Observable(obs=> { …Run Code Online (Sandbox Code Playgroud) 该文档使用以下代码描述了 tap():
import { fromEvent } from 'rxjs';
import { tap, map } from 'rxjs/operators';
const clicks = fromEvent(document, 'click');
const positions = clicks.pipe(
tap(ev => console.log(ev)),
map(ev => ev.clientX),
);
positions.subscribe(x => console.log(x));
Run Code Online (Sandbox Code Playgroud)
但我不明白为什么要使用水龙头。它只是记录。解释说
将每次点击映射到该点击的 clientX 位置,同时记录点击事件
所以要求是这样的:我得到了一个对象数组(例如数组)
[
{ empDept: 'Engineering', empLoc: 'Pune', empName: 'John' },
{ empDept: 'Engineering', empLoc: 'Mumbai', empName: 'Harry' },
{ empDept: 'HR', empLoc: 'Pune', empName: 'Denis' },
{ empDept: 'Finance', empLoc: 'Mumbai', empName: 'Elvis' },
]
Run Code Online (Sandbox Code Playgroud)
我将有一个函数,该函数将接受属性名称作为参数,员工列表将根据该名称进行分组。因此,如果输入参数值为“empDept”,那么我想要的结果如下:
[
{
key: 'Engineering',
values: [
{ empDept: 'Engineering', empLoc: 'Pune', empName: 'John' },
{ empDept: 'Engineering', empLoc: 'Mumbai', empName: 'Harry' },
]
},
{
key: 'HR',
values: [
{ empDept: 'HR', empLoc: 'Pune', empName: 'Denis' },
]
},
{
key: 'Finance',
values: [ …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 ngbootstra 订阅模式的关闭事件,但我不明白它是如何工作的。我有 2 个组件,第一个组件用于启动模式,第二个组件位于第二个组件内。
第一个
html
<button class="btn btn-lg btn-outline-primary" (click)="open()">Launch demo modal</button>
Run Code Online (Sandbox Code Playgroud)
TS
import { OtherComponent } from './../other/other.component';
import { Component, OnInit } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap/modal/modal.module';
@Component({
selector: 'app-joker',
templateUrl: './joker.component.html',
styleUrls: ['./joker.component.scss']
})
export class JokerComponent {
constructor(private modalService: NgbModal, private activeModal: NgbActiveModal) { }
open(): void{
const modalRef = this.modalService.open(OtherComponent, {centered: true});
modalRef.componentInstance.name = 'Gerardo';
}
}
Run Code Online (Sandbox Code Playgroud)
第二次
html
<div class="modal-header">
<h4 class="modal-title">Hi there!</h4> …Run Code Online (Sandbox Code Playgroud) 我目前正在使用this.route.url.subscribe(params=>...我的路线参数做一些事情。我想检查某些参数是否在订阅的param数组中。但是此数组包含URLSegments我只想从中检查path属性的数组。有什么办法可以与map操作员重新映射?
我尝试像这样重新映射整个数组,this.route.url.map(x=>x.path)但由于数组本身没有no,因此无法正常工作path。我想念什么吗?
public function(id: number) {
this.periodicCheckTimer = Observable.timer(10000, 5000).subscribe(
() => {
let model = this.find(id);
if (model['isActivated']) {
this.periodicCheckTimer.unsubscribe();
}
});
}
Run Code Online (Sandbox Code Playgroud)
如果条件if(model['isActivated'])不满足,我想在 5 分钟后自动停止计时器。但是,如果条件满足,我可以手动停止它。不确定在这种情况下手动停止是否仍然正确。
对其他计时器功能的任何建议也表示赞赏。
我想在我的全局异常处理程序中捕获HTTP错误.
异常处理程序适用于大多数异常,但不会捕获可观察的异常.我想要捕获的异常是HTTP异常.
这就是我尝试将HTTP可观察错误发送到异常处理程序的方法.
import { Injectable } from '@angular/core';
import { Request, XHRBackend, RequestOptions, Http, Response, RequestOptionsArgs } from '@angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { HttpException } from '../exceptions/http-exception';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class HttpErrorService extends Http {
constructor(backend: XHRBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs) {
return super.request(url, options).catch((error: Response) => {
// Bypass lint.
fail();
function fail() {
// Here I want to throw the exception to send it …Run Code Online (Sandbox Code Playgroud) 通过阅读一些文档和问题,我发现有一点不清楚天气使用first()或take(1)实际取消订阅完成时.我想我的困惑在于'完全'与'取消订阅'.要说一个可观察的完成,这是否也意味着订阅被取消订阅?我正在考虑这个用于垃圾收集,而我需要知道observable在first()或take(1)完成后没有保留任何引用.
如果这些功能没有取消订阅,我需要知道完成后取消订阅的最简单方法.或者这甚至是必要的吗?
angular ×9
rxjs ×5
typescript ×5
angularfire2 ×1
async-await ×1
javascript ×1
nativescript ×1
ng-bootstrap ×1