如何将这些与可观察者合并为一个?它们具有相同的功能.
this.sub = this.route.params.subscribe((params: any) => {
// functionality
});
this.sub = this.route.queryParams.subscribe((params: any) => {
// same functionality
});
Run Code Online (Sandbox Code Playgroud) 我有一个数组用户:
[0: {id:123, firstname:'xyz', lastname:'abc'}, 1:{id:456, firstname:'foo', lastname:'bar'}, 3:{id:567, firstname:'bar', lastname:'baz'}]
Run Code Online (Sandbox Code Playgroud)
我必须循环遍历此数组并调用服务API以获取用户约会.
方法1 ,我觉得这不是最佳实践,但解决问题
let userAppointments = []
for (let user of this.users) {
this._service
.getUsersAppointments(
{
date: this.todayDate,
id: user.id
},
this.token
)
.subscribe(res => {
// Modifying array as per requirements-----
userAppointments.push({
id: user.id,
name: `${user.firstname} ${user.lastname}`,
appointments: res
});
});
}
this.appointments = userAppointments
Run Code Online (Sandbox Code Playgroud)
方法2:使用forkJoin
问题:当我最终得到所有呼叫的响应时,我无法访问用户的名字和姓氏.我需要在我的最终数组this.appointments中的那些细节,即在我分配的地方调用subscribe之后res to this.appointments
forkJoin(
this.users
.map(res =>
this._service.getUsersAppointments(
{
date: this.todayDate,
id: res.id
},
this.token
)
)
.map(response => …Run Code Online (Sandbox Code Playgroud) 我有以下 Angular 7 组件:
export class PostComponent implements OnInit {
post$: Observable<PostModel>;
constructor(private postService: PostService) { }
ngOnInit() {
this.post$ = postService.getPostById(25);
}
}
Run Code Online (Sandbox Code Playgroud)
在组件模板上,我使用了以下内容:
<p>Title: {{post$.title}}</p>
Run Code Online (Sandbox Code Playgroud)
标题显示为空,我认为是因为 post$ 是一个 Observable。
使用数组时,例如posts$: Observable<PostModel[]>我将 observable 传递给模板,并且使用ngFor.
但是在这种情况下我应该怎么做呢?
用数组观察
使用数组的 Observable 时,我在 HTML 模板中有以下内容:
<div *ngIf="(posts$ | async)?.length > 0; else loading">
<ng-container *ngFor="let post of posts$ | async">
{{post.title}}
</ng-container>
</div>
<ng-template #loading>
Loading ...
</ng-template>
Run Code Online (Sandbox Code Playgroud)
这允许我在加载时显示加载消息。
我有一个带有observable的服务,通过组件订阅.当订户显示初始值时,这似乎有效.我有另一个组件,然后更新observable但是新值不会显示.
服务:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
@Injectable()
export class BannerService {
banners$: Observable<any[]> = Observable.of([]);
getBanners(): Observable<any[]> {
return this.banners$;
}
setBanners(banners: any[]): void {
this.banners$ = Observable.of(banners);
}
}
Run Code Online (Sandbox Code Playgroud)
订阅者组件:
import { Component, ViewEncapsulation, OnInit } from '@angular/core';
import { BannerService } from './../banner/banner.service';
@Component({
selector: '.banner',
templateUrl: './banner.component.html',
styleUrls: ['./banner.component.sass'],
encapsulation: ViewEncapsulation.None
})
export class BannerComponent implements OnInit {
constructor(private bannerService: BannerService){}
ngOnInit() {
this.bannerService.banners$.subscribe(banners => {
console.log(banners); …Run Code Online (Sandbox Code Playgroud) angular-services angular-components angular angular-observable
我正在构建一个自动完成功能,该功能正在查询后端以获取建议,并且只想获取用户在 Angular 5 表单控件中输入时在一定延迟的情况下进行的最后一个查询。目前我的代码看起来像
this.newVendorForm.get('address').valueChanges.pipe(delay(3000)).subscribe(
address => {
this.geocodeApi.getAddressSuggestions(address)
.subscribe(
response => {
console.log('address suggestions');
console.log(response);
this.addressSuggestions = response;
},
error => {
console.log('error getting address suggestion');
console.log(error);
}
)
}
);
Run Code Online (Sandbox Code Playgroud)
这是可行的,但是它会在 3000 毫秒后对每个输入的字母进行查询。例如,'test' 将在 3000 毫秒后查询 ['t', 'te', 'tes', 'test']。如何在 3000 毫秒延迟后从 valueChanges 中获取最后一次更改(即“测试”),然后进行订阅?谢谢你的帮助
我在服务中有以下方法来注册数据BehaviourSubject。
regFieldsModules(fieldsModules?, field?: Field) {
// Using the previously stored data from the memory
if (fieldsModules) {
this.fieldMod = fieldsModules;
}
// Stop processing if fieldModules is null/ undefined
if (!this.fieldMod) {
return;
}
const groupFields = groupBy(this.fieldMod, 'id');
const uniqueFields: Field[] = removeDuplicates(this.fieldMod, 'id');
// Find the default field and assign it to the field
if (uniqueFields && !field) {
for (const f of uniqueFields) {
if (f.isDefault) {
field = f;
}
}
this.fields.next(uniqueFields);
}
this.field.next(field); …Run Code Online (Sandbox Code Playgroud) 我对 Angular 还很陌生,我的问题可能看起来很基本,但如果能提供一些指导,我将不胜感激。我目前正在编写一个应用程序来自学一些真正的开发技能。在我的应用程序中,我有一个 Angular 组件,它导入我编写的提供数据的服务。
这是我的组件
@Component({
selector: 'music-instrument-list',
templateUrl: './instrument-report.component.html',
styleUrls: ['./instrument-report.component.css']
})
export class InstrumentReportComponent implements OnInit, OnDestroy {
constructor(public apiService: ApiService) {}
public availableInstruments: any[];
ngOnInit() {
this.apiService.getInstruments().subscribe((result) => {
this.availableInstruments = result;
});
}
ngOnDestroy() {
// how do I unsubscribe?
}
}
Run Code Online (Sandbox Code Playgroud)
这非常简单,但如果我尝试添加this.apiService.getInstruments.unsubscribe()到ngOnDestroy块中,我会收到以下错误:Type => Observable' 上不存在 Property 'unsubscribe'。我什至考虑过在类似链接.unsubscribe()之后添加.subscribe(),但这只会使我的页面挂起。我也没有收到任何错误。有人可以告诉我如何最好地取消订阅吗?我是否需要将 api 调用分配给变量,然后在块中的变量名称上使用 .unsubscribe( ngOnDestroy)
我正在尝试为用户创建一个授权系统。我正在使用 Angular11。我对 Angular 绝对是新手。我还在代码中返回一个布尔类型。但我仍然发现了一个错误。
下面是我的代码:-
auth.guard.ts
(这是主要问题)
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AccountService } from '../_services/account.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private accountService : AccountService, private toastr : ToastrService){}
canActivate(): Observable<boolean> {
return this.accountService.currentUser$.pipe(
map(user => {
if(user) return true;
this.toastr.error(error);
})
)
}
} …Run Code Online (Sandbox Code Playgroud) 加载页面时,我收到“什么是空处理”。我要获取数据列表,但无法在视图中显示这些记录。在这里我添加了代码片段来理解我的要求
Angular JS 服务文件
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class PostsService {
data: any = null;
totalDocs: number;
url: any = 'http://localhost:3000/services/';
constructor(private _http: Http) { }
public getPosts() {
return this._http.get(this.url + 'posts')
.map((res: Response) => res.json());
}
}
//End Angular JS Web service*
Run Code Online (Sandbox Code Playgroud)
从 MongoDB 获取数据的 Node JS 代码
import { default as Category} from "../models/Category";
import { default …Run Code Online (Sandbox Code Playgroud) 我正在尝试找出一种好方法来表明 ReplaySubject 当前为“空”。
import {ReplaySubject} from 'rxjs/ReplaySubject';
const rs = new ReplaySubject<Object>();
// ...
constructor(){
this.sub = rs.subscribe(...);
}
Run Code Online (Sandbox Code Playgroud)
每次调用构造函数时,它将重播主题中的所有项目。然而我的问题是 - 是否有一些我们可以监听的事件,告诉我们主题何时变空?
我唯一能想到的是在主题完成时触发自定义/不同的事件,如下所示:
rs.next({done:true});
Run Code Online (Sandbox Code Playgroud)
将数据传递给 next() 方法是表示 ReplaySubject (暂时)为空/没有事件的最佳方式吗?
我无法使用rxjs take()运算符限制模板中的显示结果,模板始终显示所有记录.
api http://jsonplaceholder.typicode.com/users返回10个元素,我只想拿四个元素.
[service]
public getData(): Observable<User[]> {
return this.http.get<User[]>(`http://jsonplaceholder.typicode.com/users`).pipe(
take(4)
);
}
[component]
export class GridComponent implements OnInit {
_data : Observable<User[]>;
constructor(public _ds : DataService) {
}
ngOnInit() {
this._data = this._ds.getData();
}
}
[template]
<tr *ngFor="let d of _data | async">
<td>{{d.id}}</td>
<td>{{d.name}}</td>
<td>{{d.email}}</td>
<td>{{d.phone}}</td>
</tr>
Run Code Online (Sandbox Code Playgroud) 我在Angular 7中使用反应形式。
我有很多字段都依赖于其他字段。
我很好奇我应该使用(change)或this.form.get("control_name").valueChanges?
对于前。两者都将在输入上起作用。我想知道它们之间的优缺点。
哪个效果更好?
angular angular-reactive-forms angular-observable angular-forms
angular ×11
rxjs ×5
typescript ×3
angular7 ×2
asp.net-core ×1
autocomplete ×1
json ×1
rxjs5 ×1
rxjs6 ×1