下的subjects
包你有这样的类PublishSubject
和BehaviorSubject
我想可以被描述为一些可用的样品Observables
.
如何取消订阅这些主题?没有unsubscribe
方法和调用onCompleted
完全结束了Observable吗?
我在服务中有以下 BehaviorSubject:
isAuthenticated = new BehaviorSubject<boolean>(false);
Run Code Online (Sandbox Code Playgroud)
我在组件中按如下方式使用它:
authenticated: Observable<boolean>;
constructor(private accountService: AccountService) { }
ngOnInit() {
this.authenticated = this.accountService.isAuthenticated.asObservable();
}
Run Code Online (Sandbox Code Playgroud)
在模板中,我执行以下操作:
<li class="login-button" *ngIf="!authenticated | async">
<a (click)="authenticate()">Log in</a>
</li>
<li *ngIf="authenticated | async">
<a>Logged in</a>
</li>
Run Code Online (Sandbox Code Playgroud)
问题是我没有看到这两个中的任何一个li
,尽管假设第一个应该出现,因为我将 Subject 的初始值分配给 false。
我究竟做错了什么?
创建RxJS时BehaviorSubject
,它会一直停留BehaviorSubject
到pipe
。一旦一个pipe
返回“d版本,它成为一个AnonymousSubject
。
// Instance of `BehaviorSubject`
const behaviorSubject$ = new BehaviorSubject({ someValue: null })
// Suddenly becomes an Anonymous Subject
const anonymousSubject$ = (
behaviorSubject$
.pipe(
pluck('someValue')
)
)
// Also suddenly becomes an Anonymous Subject
const anonymousSubject$ = (
new BehaviorSubject({ someValue: null })
.pipe(
pluck('someValue')
)
)
Run Code Online (Sandbox Code Playgroud)
我也遇到同样的问题ReplaySubject
。我似乎无法遍历该主题并将其返回。它始终会转换为AnonymousSubject
。我认为我在这里寻找的是类似Promise的行为,我可以从任何地方订阅此可观察值,并获取传递给它的一个值。
我实现了一个简单的BehaviorSubject
,
import {BehaviorSubject} from "rxjs";
class MyWeirdoClass {
constructor() {}
private st: Subject<boolean> = new BehaviorSubject<boolean>(null);
changeSt(val:boolean){
this.st.next(val);
}
val(){
this.st.subscribe(res=>{
if (res){
console.log(res);
}
})
}
stStatus() {
this.val();
this.changeSt(true);
this.val();
this.changeSt(false);
this.val();
}
}
Run Code Online (Sandbox Code Playgroud)
现在运行时stStatus()
会在控制台上记录以下输出.
true
true
Run Code Online (Sandbox Code Playgroud)
虽然我期待价值
false
true
false
Run Code Online (Sandbox Code Playgroud)
我的实施有什么问题?
所以最近我了解了 Subjects,并且我正在尝试在个人项目中使用它们。我有一个从 json 文件中获取数据并将其转换为“文章”类型的服务。Article 是一个自定义类,用于保存有关博客文章的信息。
我的最终目标是获取这个文章数组,然后当我按下 + 按钮时,它会向当前列表添加一个新的空白文章,并且视图应该通过显示具有一些默认值的空白文章来表示它。这不会保留(保存到 json)新的空白文章,而只是将其添加到当前列表中,以便视图更新并显示它。储蓄将在稍后到来。
我这辈子都不能让它发挥作用。所有文章都正确显示在我的“文章列表”页面上,但手动向其推送空白文章似乎根本没有任何作用。
这是我的服务文件
@Injectable()
export class ArticleService {
headers: Headers;
options: RequestOptions;
articles: ReplaySubject<Article[]>;
private url = 'data/articles.json';
constructor(private http: Http) {
this.headers = new Headers({ 'Content-Type': 'application/json' });
this.options = new RequestOptions({ headers: this.headers });
this.articles = new ReplaySubject<Article[]>();
}
/**
* fetch a list of articles
*/
getArticles(): Observable<Article[]> {
// no articles fetched yet, go get!
return this.http.get(this.url, this.options)
.map(response => <Article[]>response.json())
.do(data => this.articles.next(data))
.catch(this.handleError);
}
/**
* …
Run Code Online (Sandbox Code Playgroud) 我正在实现一个角度服务,让消费者根据他们的 id 观察各种值:
它的本质是这样的:
private subjects = new Map<number, Subject<any>>();
public subscribe(id: number, observer: any): Subscription {
// try getting subject for this id (or undefined if it does not yet exist)
let subj = this.subjects.get(id);
// create subject if it does not yet exist
if (!subj) {
subj = new Subject<any>();
this.subjects.set(id, subj);
}
// subscribe observer
const subscription = subj.subscribe(observer);
// set up teardown logic (gets called when subscription is unsubscribed)
subscription.add(() => {
// remove subject from …
Run Code Online (Sandbox Code Playgroud) 我正在尝试测试组件中的主题更改,但覆盖范围从未进入订阅功能。
标题栏搜索.component.ts
export class TitlebarSearch implements OnInit {
@ViewChild('titleSearchInput') titleSearchInputEl: any;
@Input() inputValue: string;
@Output() searchText = new EventEmitter<string>();
searchChange: Subject<string> = new Subject<string>();
constructor(private renderer: Renderer) {
}
/**
* Waits a time before send the text to search
*
* @protected
* @memberof TitlebarSearch
*
*/
protected prepareSearchInput() {
this.searchChange.debounceTime(500).subscribe(value => {
this.searchText.emit(value);
});
}
/**
* Send the text to the searchChange Observable
*
* @param {string} text
* @memberof TitlebarSearch
*/
public doSubmit(text:string){
this.searchChange.next(text);
}
} …
Run Code Online (Sandbox Code Playgroud) unit-testing observable subject-observer karma-jasmine angular
我想从Angular Service中检索更新的对象值(借用者).我Subject
在服务中创建了一个RxJS ,以便多个组件可以订阅它并获得更新的值.
当我通过组件中提供的服务订阅Subject时,我发现onNext()
即使.next()
从BorrowerService 调用函数参数也不会被调用.
如果我在BorrowerService类中订阅,我发现它.next()
按预期工作.似乎Subject是调用的Service类.next()
和组件之间的不同实例,因此不会获得该订阅.
这是否无法理解Angular Services或Observables?如何在不知道何时调用的情况下更新服务中的值并被动地获取组件中的更改.next()
?
借款人-report.component.ts
@Component({
...
providers: [BorrowerService]
})
export class BorrowerReport {
private borrower: Borrower;
constructor(private borrowerService: BorrowerService) {
this.borrowerService.borrowerChanged.subscribe(borrower => {this.borrower = borrower});
}
}
Run Code Online (Sandbox Code Playgroud)
borrower.service.ts
@Injectable()
export class BorrowerService {
public borrowerChanged: Subject<Borrower> = new Subject<Borrower>();
//event handler
selectBorrower(borrower: Borrower) {
this.borrowerChanged.next(borrower);
}
}
Run Code Online (Sandbox Code Playgroud) 我的代码具有Subject
,当添加新值时会触发HTTP请求,该请求返回Observable
。
我要处理两种不同的方式(使用相同的数据),这些数据并使用产生的Observables
存储group
和times
作为价值摆在ngFor
使用的async
管道。
尽管这样做确实可行,但是HTTP请求被多次发送-我只希望每个订阅一次发送一次。
下面是一个最小的示例。
import { Component, OnInit } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs/Subject";
import { ExampleService } from "../example.service";
import "rxjs/add/operator/switchMap";
@Component({
templateUrl: "./example.component.html",
styleUrls: ["./example.component.scss"]
})
export class ExampleComponent implements OnInit {
constructor(
private exampleService: ExampleService
) { }
ngOnInit() {
var selections = new Subject<string>();
var appointments = selections
// exampleService.getData returns an HTTP …
Run Code Online (Sandbox Code Playgroud) 我想构建一个包装类,它在Observable的每个发出值之前和之后执行某些操作.
这是我想出的:
class Wrapper<T> {
wrapped$: Observable<T>;
_dataSubject = new Subject<T>();
data$ = this._dataSubject.pipe(
tap(_ => console.log("BEFORE"),
//
// map( ??? )
//
);
constructor(wrapped$: Observable<T>) {
this.wrapped$ = wrapped$.pipe(
tap(_ => console.log("AFTER")
);
}
}
let subject = new Subject<string>();
let wrapper = new Wrapper(subject);
wrapper.data$.subscribe(val => console.log(val));
subject.next("foo")
Run Code Online (Sandbox Code Playgroud)
控制台输出应该是:
BEFORE
foo
AFTER
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何连接$wrapped
Observable _dataSubject
.
但也许我完全错了,需要采用不同的方法.
subject-observer ×10
rxjs ×8
angular ×7
javascript ×3
observable ×3
rxjs5 ×2
java ×1
rx-java ×1
typescript ×1
unit-testing ×1