我正在玩角度2教程的英雄应用程序,现在我有这个组件
import { Component, OnInit } from '@angular/core'
import { Subject } from 'rxjs/Subject';
import { Hero } from "./hero";
import { Router } from "@angular/router";
import { HeroService } from "./hero.service";
import { BehaviorSubject } from "rxjs/BehaviorSubject";
@Component({
selector: 'hero-search',
templateUrl: 'app/hero-search.component.html',
styleUrls: ['app/hero-search.component.css'],
})
export class HeroSearchComponent implements OnInit{
heroes: Hero[];
isLoading: BehaviorSubject<boolean> = new BehaviorSubject(false);
error: any;
private searchNameStream = new Subject<string>();
constructor(
private heroService: HeroService,
private router: Router
) {}
ngOnInit() {
this.searchNameStream
.debounceTime(400)
.distinctUntilChanged()
.switchMap(name …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Resolve设置我的路由器配置,它从BehaviorSubject返回一个Observable.我在角度4.0.0-beta8和角度2.4.8 +路由器3.4.8中尝试了这个
这是我的服务:
@Injectable()
export class MyService {
private _data: BehaviorSubject<Array<string>> = new BehaviorSubject(undefined);
constructor() {}
public getData(): Observable<Array<string>> {
this._data.next(['test1', 'test2', 'test3']);
let asObservable = this._data.asObservable().delay(1000);
asObservable.subscribe((myData) => {
console.log([myData, 'this console message DOES show up']);
});
// if I return here, my component's constructor and ngOnInit never fire
// return asObservable;
let fakeObservable = Observable.of(['test1', 'test2', 'test3']).delay(1000);
fakeObservable.subscribe((fakeData) => {
console.log([fakeData, 'this console message shows up']);
});
console.log([asObservable, fakeObservable]);
/* console log output
Observable {
_isScalar: false,
operator: …Run Code Online (Sandbox Code Playgroud) 我有一个方法需要等待一个observable完成.我知道observable非常适合随着时间的推移返回单个数据,但是我需要知道这个observable何时完全返回它的所有数据,所以我可以在它返回的对象上运行验证代码.
getCustom方法订阅了提供的url上的可观察运行,然后返回observable.
我不太确定这是否是解决这种情况的最佳方式,所以如果有人能给我任何建议或方向来处理这个问题,我将不胜感激.
private validateQuoteRetrievalAnswers(reference: string) {
// Get the risk from the server
this.riskManager.getRiskFromServer(reference);
if (this.riskManager.risk) {
// Validate risk that was returned
}
}
Run Code Online (Sandbox Code Playgroud)
getRiskFromServer(quoteReference: string) {
this.riskService.getCustom("Url").subscribe => {
// need to know when the observable has returned the risk
});
}
Run Code Online (Sandbox Code Playgroud) 我正在编写带有通过 RxJs observables 实现的间隔计时器的 angular2 应用程序,并且刚刚注意到当选项卡处于后台时 Chrome 浏览器中 Observable.interval() 和 Observable.timer() 的奇怪行为。Angular 组件应该每秒在控制台中打印一次秒数,但在后台选项卡上,这无法按预期工作 - 函数每 x+1 秒触发一次,其中 x 是间隔函数中明确指定的间隔
角度组件代码:
ngOnInit() {
let a = Observable.interval(1000).subscribe(() => {
let date = new Date();
console.log(date.getSeconds());
});
}
Run Code Online (Sandbox Code Playgroud)
示例:tab1 上的控制台输出(带有上面定义的计时器的选项卡):
37 <- tab1 (with timer)
38
39
40
41 <- changed tab to tab2
43
45
47
49
51
53
55
57
59 <- changed tab to tab1
0
1
2
3
Run Code Online (Sandbox Code Playgroud)
Mozzila FF 没有问题。
我认为这种行为是浏览器中后台选项卡优先级较低的结果,但为什么间隔总是推迟一秒?
我无法解决角度4预检请求未通过CORS访问控制检查的问题:"No'Access-Control-Allowed-Origin'".我能够从数据库中成功获取数据,但无法发布/保存数据.我正在使用前端的VS代码访问我的Visual Studio 2015后端.我的Web Api控制器具有以下属性:
[EnableCors(origins: "*", headers: "*", methods: "*")]
[HttpPost]
public async Task<IHttpActionResult> Post([FromBody]Employee employee)
{
_repo.Create(employee);
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
...但是在提出请求时,我收到的错误是:
XMLHttpRequest无法加载http:// localhost:54429/api/createEmployee /.对预检请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许来源' http:// localhost:4200 '访问
在我的vs代码中,我的服务看起来像这样:
postEmployeeForm(employee: Employee): Observable<any>{
let body = JSON.stringify(employee);
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
console.log('posting employee ' , employee);
return this.http.post("http://localhost:54429/api/employees/", body, options)
.map(this.extractData)
.catch(this.handleError)
}
Run Code Online (Sandbox Code Playgroud)
405从帖子中删除正文和选项后的响应.
不确定我错过了什么.
网络配置
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 …Run Code Online (Sandbox Code Playgroud) cors asp.net-web-api preflight angular2-forms angular2-observables
我正在编写一个Angular 4应用程序HttpClient,用于显示电影放映时间.数据所在的有2个JSON文件:showtimes.json和movies.json.
// showtimes.json
[{
"id": "2030c64ce72b4e4605cb01f2ba405b7d",
"name": "Arclight", // need to display this information
"showtimes": {
"b4c2c326a4d335da654d4fd944bf88d0": [ // need to use this id
"11:30 pm", "2:45 pm", "8:35 pm", "4:15 pm", "10:30 pm"
]
}
}]
// movies.json
[{
"b4c2c326a4d335da654d4fd944bf88d0": { // to retrieve the title, rating, and poster
"title": "Fifty Shades Darker", // needs to be displayed
"rating": "R", // needs to be displayed
"poster": "https://dl.dropboxusercontent.com/s/dt6wgt92cu9wqcr/fifty_shades_darker.jpg" // needs to be displayed …Run Code Online (Sandbox Code Playgroud) 我试图从一个压缩的 observables 数组中得到结果,这些压缩数组本身就是一个简单的 observables 数组的压缩包。如下:
a(x) {
const observables = [of(x), of(x+1)];
return zip(observables);
}
b() {
const observables = [a(1), a(2)];
return zip(observables);
}
Run Code Online (Sandbox Code Playgroud)
其余的代码被断言可以正常工作。实际上,当内部 a() 函数返回单个 observable(当然是对象数组,以反映 observable 的 zip)时,外部 zip 工作正常。然而,当使用内拉链时,内拉链内的代码永远不会被调用。
我在这里做错了什么?
Observables我对 Angular 4 以及与之相关的一切都很陌生。我试图http依次执行两个请求(仅当第一个请求成功时)。
我正在使用这段代码:
public getCompany(id: string): any {
let company = null;
this.authService.isValidUser().subscribe(response => {
const token = this.tokenStorageService.getTokenFromStorage();
const requestUrl = environment.gatewayUrl + environment.companyService + environment.getCompanyEndPoint + id;
const headers = new Headers();
headers.set('Authorization', 'Bearer ' + token);
const options = new RequestOptions({headers: headers});
return this.http.get(requestUrl, options).catch(this.errorService.handleError);
}, (error: AppError) => {
// ........ //
});
}
Run Code Online (Sandbox Code Playgroud)
这是isValidUser()方法代码:
public isValidUser(): any {
const token = this.tokeStorageService.getTokenFromStorage();
if (!token) {
console.log('cannot …Run Code Online (Sandbox Code Playgroud) 我有一项与第三方服务通信的服务。该服务由应用程序中的多个组件执行。每当服务失败时(“DoSomethingWhenFails”函数),我希望在通用通知组件中收到通知。目前,通用通知组件在 app.component 中引用,并且服务被注入到该组件中。
我想到了类似 eventEmitter 的东西,它会在服务中发出,但是在注入服务时我不熟悉这种模式。最好的方法是什么?看我的代码:
应用程序组件.html:
<notify #messageBox ></notify>
Run Code Online (Sandbox Code Playgroud)
组件:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
@ViewChild('messageBox') messageBox : notify;
constructor(private someService: SomeService )
Run Code Online (Sandbox Code Playgroud)
通用通知组件:
export class notification
{
ShowNotificationWhenTheServiceFails()
{
DoSomethig();
}
}
Run Code Online (Sandbox Code Playgroud)
服务:
@Injectable({
providedIn: 'root'
})
export class Service{
doSomething(): Observable<any> {
return this.http.get<AA>(URL, options).pipe(
connectToThirdPArtyService();
}),
DoSomethingWhenFails();
);
}
Run Code Online (Sandbox Code Playgroud) 我遇到了 Angular 的情况,其中路由数据解析器似乎准备正确返回数据,但解析从未发生。这特别奇怪,因为我有另一个组件的平行排列,并且在那里工作正常。
该应用程序通过 HTTP 检索有关一系列事件的数据。在 中EventListComponent,解析器返回所有事件以响应/events,并且组件正确显示它们。在一个EventDetails组件中,在我目前的安排中,我仍然通过 HTTP 检索所有事件,然后在解析器中响应/events/[the event ID],选择应该显示其详细信息的事件。(这是来自 Pluralsight Angular Fundamentals 课程,以防它听起来很熟悉。但我倾向于观看视频,然后按照我自己的顺序完成它们,以尝试巩固我头脑中的技能。)
远程事件.service.ts
import { Injectable, EventEmitter } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { IEvent } from './event.model';
@Injectable()
export class RemoteEventService {
constructor(
private http: HttpClient
) {}
getEvents(): Observable<IEvent[]> {
return this.http.get<IEvent[]>('/api/ngfdata/events.json');
}
getEventById(id: number): Observable<IEvent> {
console.log(`In getEventById: id = ${id}`);
const emitter = new EventEmitter<IEvent>(); …Run Code Online (Sandbox Code Playgroud) angular ×8
observable ×4
rxjs ×3
typescript ×3
cors ×1
preflight ×1
resolve ×1
rxjs5 ×1
timer ×1