我正在尝试将Observable转换为BehaviorSubject。像这样:
a$ = new Observable()
b$ = BehaviorSubject.create(new BehaviorSubject(123), a$)
//
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
a$ = new Observable()
b$ = new BehaviorSubject(a$, 123)
//
Run Code Online (Sandbox Code Playgroud)
和:
a$ = new Observable()
b$ = a$.asBehaviorSubject(123)
//
Run Code Online (Sandbox Code Playgroud)
和:
a$ = new Observable()
b$ = a$.pipe(
toBehaviorSubject(123)
)
//
Run Code Online (Sandbox Code Playgroud)
但是这些都不起作用。现在,我必须像这样实现:
a$ = new Observable()
b$ = new BehaviorSubject(123)
a$.subscribe(b$)
//
Run Code Online (Sandbox Code Playgroud)
在课堂上,这有点难看:
class Foo() {
a$ = new Observable() // Actually, a$ is more complicated than this.
b$ = new BehaviorSubject(123)
constructor() {
this.a$.subscribe(this.b$)
}
}
Run Code Online (Sandbox Code Playgroud)
因此,有没有更简单的方法可以在不使用类构造函数的情况下将Observable转换为BehaviorSubject?
这是我的真实情况: …
在使用 Ionic 3 应用程序时,我遇到了一个问题,即当您observable从 service in订阅ngOnInit并将局部变量更新到其中时,它不会更新视图。
例如 HTML 模板
<p>{{myVariable}}</p>
constructor(myService: MyService) {
}
ngOnInit() {
this.myService.myObservable.subscribe((data) => {
this.myVariable = data;
});
}
Run Code Online (Sandbox Code Playgroud)
但是当你从构造函数做同样的事情时,它就起作用了。
contructor(myService: MyService) {
this.myService.myObservable.subscribe((data) => {
this.myVariable = data;
});
}
Run Code Online (Sandbox Code Playgroud)
它是一个 Ionic 3 应用程序。它包含不同的离子标签。问题是当您订阅时视图不会自动更新ngOnInit。您可以在选项卡之间切换以使其工作。但是当您订阅 constructor 它时,它无需切换标签即可工作。
知道为什么会这样。任何提示将不胜感激。谢谢。
我需要在标题中显示路由组件的标题.但是当我在我的应用程序中使用ngOnInit时,它获得了默认值.即使通过服务更改变量值,它也不会改变.怎么做?
Data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class DataService {
public myGlobalVar : string = "Chaitanya";
constructor() { }
setMyGV(val : string){
this.myGlobalVar = val;
console.log(this.myGlobalVar);
}
getMyGV(){
return this.myGlobalVar;
}
}
Run Code Online (Sandbox Code Playgroud)
header.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from 'src/app/data.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
public title : string = '';
constructor(private _emp : DataService) { …Run Code Online (Sandbox Code Playgroud) 我在组件中定义了一个可观察的(result $),并通过异步管道将其显示在其模板上。可观察值是通过CombineLatest将其他2个可观察值(first $,second $)组合而成的。如果其中一个或两个可观察对象发出的时间过早(在我发现ngAfterContentInit之前),则所得的可观察对象将不会发出值。
组件:不起作用
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
result$: Observable<number>;
first$ = new Subject<number>();
second$ = new Subject<number>();
constructor() {}
ngOnInit(){
this.result$ = combineLatest(
this.first$,
this.second$
).pipe(
map(([first, second]) => {
// This is not printed to the console
console.log('combined obs emitted value');
return first + second;
})
);
console.log('first and second emit value');
this.first$.next(2);
this.second$.next(4);
}
ngAfterContentInit() {
console.log('ngAfterContentInit');
}
}
Run Code Online (Sandbox Code Playgroud)
执行顺序为:
1.第一和第二发射值
2.ngAfterContentInit
我在这里的假设是,在ngAfterViewInit中,模板已渲染,并且已进行预订。因为可观察对象在此之前发出一个值,所以不会通知组件。这仅意味着结果的可观察对象是冷的(因此,您需要在其发出值之前进行预订)。这两个可观察对象是对象,因此我认为对象是冷可观察对象。它是否正确?
如果我延迟了first $和second $的发射,则一切正常:Component:first …
我有一项服务从服务器获取一些数据并更新一些主题,在我的组件的 ngOnInit 函数中我正在订阅该主题。我已确认主题已正确更新。
以下是我的服务功能,它从服务器获取数据并更新主题。
getInboxData(id?) {
this.inboxID = id;
this.loadingData.next( // tells to start showing loading animation
{
showloading: true,
clearDocuments: this.shouldClearDocuments()
});
this.getInboxCount();
this.dashboardService.getInbox(id, this.page)
.subscribe((response) => {
for (const inbox of response['results']) {
this.documents.push(inbox.document);
// tells to stop showing loading animation
this.loadingData.next({showloading: false, clearDocuments: this.shouldClearDocuments()});
}
if (response.next != null) {
this.page++;
// this.getInboxData(id);
}else {
this.page = 1; // reset
}
this.documentsData.next(response);
});
}
Run Code Online (Sandbox Code Playgroud)
我正在我的组件中订阅documentsData。以下是组件的代码。
ngOnInit() {
this.dashboardDataService.getInboxData();
this.dashboardDataService.documentsData
.subscribe((response) => {
this.isLoadingMoreResult = false; …Run Code Online (Sandbox Code Playgroud) 是否可以在服务中使用主题进行 2 向数据流?例如,假设我希望某个组件检索信息,然后通过服务 Subject 将其发布以供其他组件使用。
消费组件然后对该信息进行一些更改,然后重新发布它,以便原始组件可以检索更改。
这可以使用观察者模式吗?
另外,如果我想查看这些数据的变化(假设数据是通过数组传入的),我是否必须使用代理来完成此操作?
我有一个共享服务如下:
data = new BehaviorSubject<any[]>([]);
constructor(userService: UserService){
if (localStorage.getItem('data') === null) {
userService.getAllData().subscribe(results =>
this.data.next(results)
}
else {
this.loadData()
}
}
loadData() {
let data = JSON.parse(localStorage.getItem('data');
this.data.next(data);
}
setData(data) {
localStorage.setItem('data', JSON.stringify(data))
this.data.next(data)
}
Run Code Online (Sandbox Code Playgroud)
然后在我的 ngOnInit() 组件上,我有:
ngOnInit() {
this.sharedService.data.subscribe(results =>
this.allData = results;
)
}
itemChange() {
this.allData.slice(index, 5);
this.sharedService.data.next(this.allData)
}
Run Code Online (Sandbox Code Playgroud)
和 OnLogout 我有:
localStorage.removeItem('data')
Run Code Online (Sandbox Code Playgroud)
问题是在第一页重新加载时,服务被调用并且我按预期获得了数据,我进行了更改,然后在我注销并重新登录后,在存储上我不再拥有数据密钥,但是sharedService 不会再次被调用,而是在this.sharedService.data上次填充的onInit 组件上。
我如何让它每次都调用 sharedService 以便它检查 item('data') 是否存在,就像它在服务构造函数上一样?
我有组件 A、组件 B 和一项服务。我在服务中声明了 Subject 并订阅了组件 B. 中的主题,并且在导航到组件 B 之前,我将一些数据从组件 A 发送到主题。它正在导航到组件 B,但没有触发订阅方法。
服务:
@Injectable({
providedIn: 'root'
})
export class ServiceTestService {
storage: Recipe;
recipeSelected = new Subject<any>();
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
组件 A向 observable 发送消息
@Component({
selector: 'app-recipe-item',
templateUrl: './recipe-item.component.html'
})
export class RecipeItemComponent implements OnInit {
@Input() recipe: Recipe;
constructor(
private recipeService: ServiceTestService,
private rt: Router) { }
ngOnInit() {
}
onRecipeSelected(name: number) {
this.recipeService.recipeSelected.next(this.recipe);
this.rt.navigate(['/recipe', this.ind]);
}
}
Run Code Online (Sandbox Code Playgroud)
组件 B: 这里我订阅了 Observable。
@Component({
selector: 'app-recipe-detail',
templateUrl: …Run Code Online (Sandbox Code Playgroud) 据我所知,我们在组件间和组件内通信的情况下使用服务,其中我们隐藏了多个或复杂的数据结构。我们真的只在持久化数据结构的情况下使用服务吗?那么在哪些情况下我们不应该使用服务呢?
我已经检查了这个https://github.com/angular/angular/issues/12129 但我没有看到任何解决方案......
Angular 2.0.1 AsyncPipe 不适用于 Rx Subject。
这里的解决方法是在组件中创建一个可观察的变量
我有但仍然没有工作......不知道为什么它不起作用,如果我将我的主题切换UserStateService到 BehaviorSubject 一切正常......
注意:UserDataService 和 UsersStateService 都在根 app.module.ts 中提供。
user-data.service.ts -> 发出我在组件中调用的 http 请求
fetchUsers():void{
this.httpClient.get<User[]>(this.apiUrl, {
observe: 'body',
responseType: 'json'
})
.subscribe( (response: User[])=>{
this.usersStateService.setUsersList(response); <-- set to local state service
});
}
Run Code Online (Sandbox Code Playgroud)
用户状态.service.ts
userListState = new Subject<User[]>(); <-- Change this to BehaviorSubject<User[]>([]) everything works!
setUsersList(users: User[]):void {
this.userListState.next(users.slice());
}
getUsersListState():Observable<User[]>{
return this.userListState.asObservable();
}
Run Code Online (Sandbox Code Playgroud)
组件.ts
users: Observable<User[]>;
ngOnInit() {
if(this.usersStateService.hasUserList()){
this.users = this.usersStateService.getUsersListState(); -|
|
// …Run Code Online (Sandbox Code Playgroud) 我正在学习Angular,目前我的话题是Observables。我现在了解什么是可观察对象,包括主题,BehaviorSubject,ReplaySubject。但是我需要一个真实的示例,在这些示例中可以实际实现这些示例,因此我可以理解何时使用哪种方法。
例如,在我可以看到/比较上述方法的实现的任何应用程序中。
我有一个带有 RXJS 主题的服务,并且我正在将数据分配给构造函数内的主题进行 api 调用。我在组件模板中订阅了该主题。尽管数据已提供给受试者,但它不会在第一次时立即发射。
interface Employee {
employee_age: number;
employee_name: string;
employee_salary: number;
id: string;
profile_image: string;
}
@Injectable({
providedIn: "root",
})
export class EmployeeService {
employeesSub = new Subject<Employee[]>();
employees: Employee[];
constructor(private http: HttpClient) {
this.api().subscribe((res) => {
this.employees = res.data;
this.employeesSub.next(this.employees);
});
}
getEmployees(){
this.employeesSub.next(this.employees);
}
addEmployee(name,age,salary) {
this.employees.unshift({
id:(this.employees.length + 1).toString(),
employee_age: age,
employee_name: name,
employee_salary: salary,
profile_image: ""
});
this.employeesSub.next(this.employees);
}
api() {
return this.http
.get<any>(environment.employeeUrl)
.pipe(map((data) => data.items));
}
}
Run Code Online (Sandbox Code Playgroud)
模板中的代码
<h2>List</h2>
<div style="display: …Run Code Online (Sandbox Code Playgroud)