我一直在寻找那些3:
主题,行为主体和重播主题.我想使用它们,知道何时以及为什么,使用它们有什么好处,虽然我已阅读文档,观看教程和搜索谷歌,但我没有对此有任何意义.
那他们的目的是什么?一个真实的案例将是非常感谢它甚至不必编码.
我更喜欢一个干净的解释,而不只是"a + b => c,你订阅了......"
谢谢
javascript reactive-programming rxjs angular2-observables angular
可以使用angular cli生成服务,并在app.module.ts中将其作为提供程序添加到一个步骤中,或者使用ng g service命令中的特殊选项?
执行时:
$ ng g service services/backendApi
installing service
create src/app/services/backend-api.service.spec.ts
create src/app/services/backend-api.service.ts
WARNING Service is generated but not provided, it must be provided to be used
Run Code Online (Sandbox Code Playgroud)
在它旁边,(并根据警告消息)我通常使用文本编辑器将它添加到app.module.ts上的提供程序部分:
@NgModule({
declarations: [
AppComponent,
...
],
imports: [
....
],
providers: [BackendApiService],
bootstrap: [AppComponent]
})
Run Code Online (Sandbox Code Playgroud)
只需一步就可以实现自动化吗?
也许我错过了什么.我找不到Observable及其语法的简单教程.我正在使用Angular,我需要从服务中调用一个函数(在一个组件中定义).我读了这个解决方案.但我无法弄清楚如何更改服务中创建的Observable中的值(可能创建不是最好的方法).
我有一个像解决方案中的组件:
@Component({
selector: 'my-component',
...
)}
export class MyComponent {
constructor(myService:MyService) {
myService.condition.subscribe(value => doSomething(value));
}
doSomething(value) {
if (value) // do stuff
else // other stuff
}
Run Code Online (Sandbox Code Playgroud)
}
这是我的服务:
import { Injectable } from '@angular/core';
import { Observable} from 'rxjs/Observable';
@Injectable()
export class MyService {
private condition: Observable<boolean>;
constructor() {
this.condition= new Observable(ob => {ob.next(false); })
// maybe ob.next is not the best solution to assign the value?
}
change() {// how can i change the …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个observable,当localStorage变量发生更改时返回值.我的订户在更改localStorage时(或者在内存变量中)没有获得新值.
import { Component, OnInit } from '@angular/core';
import { UserService } from '../services/user.service';
/**
* This class represents the navigation bar component.
*/
@Component({
moduleId: module.id,
selector: 'sd-navbar',
templateUrl: 'navbar.component.html',
styleUrls: ['navbar.component.css'],
providers: [UserService]
})
export class NavbarComponent implements OnInit {
loggedIn: boolean;
constructor(private us: UserService) { }
ngOnInit() {
this.us.isLoggedIn().subscribe(loggedIn => {
this.loggedIn = loggedIn;
});
}
}
Run Code Online (Sandbox Code Playgroud)
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UserService } from …Run Code Online (Sandbox Code Playgroud) 目前,有一种情况是多个组件使用共享服务中的方法.此方法对端点进行HTTP调用,该端点始终具有相同的响应并返回Observable.是否可以与所有订阅者共享第一个响应以防止重复的HTTP请求?
以下是上述方案的简化版本:
class SharedService {
constructor(private http: HttpClient) {}
getSomeData(): Observable<any> {
return this.http.get<any>('some/endpoint');
}
}
class Component1 {
constructor(private sharedService: SharedService) {
this.sharedService.getSomeData().subscribe(
() => console.log('do something...')
);
}
}
class Component2 {
constructor(private sharedService: SharedService) {
this.sharedService.getSomeData().subscribe(
() => console.log('do something different...')
);
}
}
Run Code Online (Sandbox Code Playgroud) 我对Observables很新.我如何从一个简单的字符串创建Observable?然后订阅它并在它改变时输出它.
那有意义吗?
谷歌搜索我没有运气.可能错误的关键字?
添加一些代码以获得更好的解释
My constructor on service
constructor() {
// Create observable stream to output our data
this.notice = Observable.create(
(observer) => this.observer = observer;
);
};
My method on service
set(string) {
this.notice.subscribe((value) => {
// Push the new value into the observable stream
this.observer.next(string);
}, (error) => console.log('Could not set data.'));
}
Calling service method
setNotice(event) {
event.preventDefault();
// Calling service to set notice
this.noticeService.set('This is a string');
}
Run Code Online (Sandbox Code Playgroud)
我想我在这里做错了什么?但不知道该怎么问.我将不胜感激任何解释.
我正在构建一个垂直滚动的日历。我正在加载最初的日子,但是当新的日子添加到列表中时,它们不会被呈现。
<cdk-virtual-scroll-viewport
class="demo-viewport"
[itemSize]="100"
(onContentScrolled)="handleScrollChange($event)"
>
<calendar-day
*cdkVirtualFor="let day of days; trackBy: trackByFn"
[day]="day"
></calendar-day>
</cdk-virtual-scroll-viewport>
<button (click)="goToToday()">go</button>
Run Code Online (Sandbox Code Playgroud)
我有一项BehaviorSubject更新天数的服务。我知道天数列表正在更新,但似乎没有检测到更改。
ngOnInit() {
this._daysService.days$.subscribe(days => {
this.days = days;
})
this.watchScroll();
this.handleScrollingUp();
this.handleScrollingDown();
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,StackBlitz 存储库是公开的https://stackblitz.com/edit/material-infinite-calendar
我是Observable样式编程的新手.我有一个问题:我希望在组件之间跨应用程序共享用户信息 - 我使用BehaviorSubject来共享此信息.这是通过将BehaviorSubject共享为AuthInfo来启发的.如果我可以在我的应用程序组件中共享包含uid的AuthInfo,为什么我可以使用它来共享我的用户对象数据?
问题是,用户对象,我是从Firebase获得的.所以它是一个Observable,我不知道如何将它分配给一个行为主题.所以这是我尝试的代码:
@Injectable()
export class AuthService {
static UNKNOWN_USER = new AuthInfo(null);
static EMPTY_USER = new User(null, null, null, null);
authInfo$: BehaviorSubject<AuthInfo> = new BehaviorSubject<AuthInfo>(AuthService.UNKNOWN_USER);
userInfo$: BehaviorSubject<User> = new BehaviorSubject<User>(AuthService.EMPTY_USER);
constructor(private auth: FirebaseAuth, private db:AngularFireDatabase, @Inject(FirebaseRef) fb) {
//firebase way to see if user is login or not
this.auth.subscribe(user => {
if (user) {
const authInfo = new AuthInfo(user.uid);
this.authInfo$.next(authInfo);
//This is the part I do not know how to do
[OPTION 1]: this.userInfo$.next(findUserByuid(user.uid)) ?? - error
[OPTION …Run Code Online (Sandbox Code Playgroud) Im using BehaviourSubject from RxJS:
private rights = new BehaviorSubject<Array<string>>([]);
updateRights(rights: Array<string>) {
this.rights.next(rights);
}
getRights(): Observable<any> {
return this.rights.asObservable();
}
Run Code Online (Sandbox Code Playgroud)
I'm updating the rights in the root component and im subscribing to it in another component like:
this.configService.getRights().subscribe(res => {
console.log(res);
})
Run Code Online (Sandbox Code Playgroud)
This subscription is firing twice. Once when the data is empty and then again when the data is received.
I want the subscription to fire only once and get only the latest data. What should be done?
在Angular 4.x中使用RxJS时,我看到了两种非常不同的模式,用于从用户启动的动作流中生成Observable。一个流是用户单击生成新对象的“添加项目”按钮的直接结果。另一个是由我正在使用的某些第三方代码发出的一系列事件。
我希望能够使用“ combineLatest”之类的东西来组合这两个流以生成单个Observable。
使用我的按钮,我遵循以下模式:
const signal = Observable.create(
(observer) => {
this.additem= (item) => observer.next(item);
}
);
this.item$ = signal.map((item) => [item])
.scan((accumulator, value) => {
return accumulator.concat(value);
});
Run Code Online (Sandbox Code Playgroud)
但是,我看到很多信息说我应该改用Subjects-我正尝试将其与事件回调一起使用,如下所示:
sort$ = new Subject();
sortChange(sort){
sort$.next(sort);
}
Run Code Online (Sandbox Code Playgroud)
然后,我尝试将这些合并如下:
combine$ = Observable.combineLatest(sort$, item$,
(sort, items) => {
return "something that does stuff with these";}
);
Run Code Online (Sandbox Code Playgroud)
我的问题是-“手动”生成流的首选模式是什么?是否可以/应该像我在这里尝试的那样将可观察对象和主题网格化为一个可观察对象?
angular ×8
rxjs ×6
observable ×3
typescript ×3
javascript ×2
angular-cli ×1
angular6 ×1
angular7 ×1
rxjs6 ×1