我有一个注入了服务的组件(我的数据存储),它从其他 http 服务提供数据。您可以通过延迟加载路由配置(loadChildren)来访问该组件。
当用户注销(到另一个不同的路线)并立即使用不同的用户登录(一个人可以维护两个用户)时,商店服务之前(旧用户)提供相同的数据,当我认为它应该收取新数据时(新用户)。
我认为当用户注销时,服务应该被“销毁”,因为服务观察者被销毁(在 ngOnDestroy 中),并且不需要以再次构建服务的方式进行注入。
我知道该组件可以使用另一种方法从服务获取新的数据,但我认为该服务已经应该从 Constructor-ngOnInt 获取数据。问题是服务没有被破坏、清除......并且数据仍然来自旧用户。
这是我的代码。
成分
constructor(
public busquedasStore: BusquedasStore) { }
ngOnInit() {
this.busquedasSubs = this.busquedasStore.busquedas.subscribe(b => {
this.busquedas = b;
})
ngOnDestroy() {
this.busquedasSubs.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)
服务
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { BehaviorSubject } from "rxjs/BehaviorSubject";
import { UserService } from '../../core/user.service';
@Injectable()
export class BusquedasStore {
busquedas$: BehaviorSubject<{}[]> = new BehaviorSubject([]);
constructor(
public userService:UserService
) {
this.cargarDatosIni();
}
cargarDatosIni() {
this.userService.me().subscribe((res) => { …Run Code Online (Sandbox Code Playgroud) 我有一个Angular 4登录应用程序.我已经在login.cmponent.ts文件中编写了访问逻辑并访问了我的login.service.ts文件,该文件又调用了一个身份验证服务.
当我从登录组件调用authenticate方法时,它返回false.当它执行剩余代码时,身份验证服务返回true,因为我们以异步方式知道Angular运行代码.
这是我的代码:
登录组件方法:
this.loginService.setLoginData(
new LoginModel( this.userId, this.bankId, this.password )
).checkIfLoginSuccessfull();
Run Code Online (Sandbox Code Playgroud)
Login.service方法:
this.authService
.attemptAuth(credentials);
Run Code Online (Sandbox Code Playgroud)
验证服务方法:
attemptAuth(credentials): void {
this.restService
.post('/authenticate', credentials)
.subscribe(
data => this.setAuth(data.token),
err => this.destroy());
}
Run Code Online (Sandbox Code Playgroud)
代码工作正常.但是我想在执行checkIfLoginSuccessfull()的那一刻得到结果.我知道我没有做或调用方法(Observables正确).
请帮忙.:)
我想将 a 的最后一个值重新发送BehaviourSubject到现有订阅。我试过last(),publishlast(),share(),refcount()。但它不会使用上次发出的值再次触发现有订阅。
我已经在我的service.ts中定义了主题
,onEditItem()其中detail.component.ts传递了 id 的值,并且在new.component.ts.next()中订阅了主题
,但订阅不起作用。订阅是在new.component.ts 中完成的ngOnInit
id 值传入成功,onEditItem()但订阅失败。我尝试在订阅内进行 console.log 检查。但控制台中没有打印任何内容。
在details.component.html中
<a class="btn btn-primary" (click)="onEditItem()" routerLink="/new">Edit</a>
Run Code Online (Sandbox Code Playgroud)
在详细信息.component.ts中
onEditItem(){this.contactService.startedEditing.next(this.id);}
Run Code Online (Sandbox Code Playgroud)
在contactService.ts中
export class ContactService {
startedEditing =new Subject<number>();
}
Run Code Online (Sandbox Code Playgroud)
在new.component.ts中
ngOnInit() {
this.subscription = this.contactService.startedEditing.subscribe(
(index: number) => {
console.log(index);
this.editedItemIndex = index;
console.log(this.editedItemIndex);
this.editMode = true;
this.editedItem = this.contactService.getContacts(index);
this.editForm.setValue({
name: this.editedItem.name,
address: this.editedItem.address
})
}
);
}
Run Code Online (Sandbox Code Playgroud)
我预计中定义的表单new.component.html应使用详细信息组件中的值进行初始化,但订阅在 中不起作用ngOnInit。
observable subject-observer behaviorsubject angular2-observables angular
这是我的代码:
this._http.post(this._url_get + extension, '', { headers: headers })
.map(res => res['_body'])
.retryWhen(errors => {return responseErrorProcess(errors)})
Run Code Online (Sandbox Code Playgroud)
现在我需要捕获异常并将它们传递给我responseErrorProcess(),true如果它需要重试则返回
我无法弄清楚如何从中检索异常errors,这是它的样子:
Subject_isScalar: falseclosed: falsehasError: falseisStopped: falseobservers: Array[0]thrownError: null__proto__: Observable`
Run Code Online (Sandbox Code Playgroud)
它似乎没有包含有关发生的异常的错误,而且我无法弄清楚应该返回什么以便实际重试.
我正在学习Angular2。我正在使用带有Observable的LocationService,它在一段时间后将坐标传递给我。这是我的代码。
location.service.ts
public getLocation(): Observable<any> {
return Observable.create(observer => {
if(window.navigator && window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(
(position) => {
observer.next(position);
observer.complete();
},
(error) => observer.error(error)
);
} else {
observer.error('Unsupported Browser');
}
});
}
Run Code Online (Sandbox Code Playgroud)
app.component.ts
ngOnInit() {
this.location.getLocation().subscribe((coordinates) => {
this.lat = coordinates.coords.latitude;
this.lng = coordinates.coords.longitude;
});
}
Run Code Online (Sandbox Code Playgroud)
我如何订阅坐标的接收,以便一旦我从第一个订阅中收到坐标后就可以渲染地图,添加标记。
按照教程,教师正在使用spotify api构建spotify音乐搜索.按照教练所做的每一步,但问题是我的数据永远不会回来,我得到了未定义,没有任何东西出现在屏幕上.但是,如果我直接在浏览器中点击api,则会显示json数据,但不会在我的应用中显示.
其实我已经看过很多像这样的问题,但没有一个能解决我的问题.我认为它可能是一个与网络相关的问题,但是当我设置断点时,我可以在响应中看到结果,但是没有任何东西被加载到视图中,未定义被加载到控制台中
**search.component.html**
<h1>Need Music?</h1>
<p class="lead">
Use the ngSpotify app to browse new releases of your favorite songs. See what your favorite artistes are up to.
</p>
<form>
<div class="form-group">
<input type="text" name="searchStr" [(ngModel)]="searchStr" (keyup.enter)="searchMusic()" class="form-control" placeholder="Search music here..."/>
</div>
</form>
**search.component.ts**
import { Component, OnInit } from '@angular/core';
import { SpotifyService } from '../../Services/spotify.service';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
constructor(private _spotifyservice: SpotifyService) { }
searchStr: string;
searchResult;
searchMusic() …Run Code Online (Sandbox Code Playgroud) 我在Angular应用程序中成功使用了Observables.到目前为止,我已经在组件中明确订阅,然后使用*ngFor迭代视图中的记录数组.现在我想通过在各种视图中使用Angular的异步管道来简化事情 - 这样就可以处理订阅和取消订阅.到目前为止,这是行不通的.
这就是我原来的(我在组件中订阅的地方):
ngOnInit() {
this.clientService.getAll(1, this.pagesize)
.subscribe(resRecordsData => {
this.records = resRecordsData;
console.log(this.records);
},
responseRecordsError => this.errorMsg = responseRecordsError);
}
Run Code Online (Sandbox Code Playgroud)
然后在视图中我做了以下事情:
<tr *ngFor="let record of records.data>
Run Code Online (Sandbox Code Playgroud)
顺便说一句,来自API的数据结构看起来像这样(我正在迭代的记录在"data"数组中,因此在上面的*ngFor中的"records.data"):
{
"count": 15298,
"data": [
{
Run Code Online (Sandbox Code Playgroud)
因此,为了转向使用异步管道,我将组件ngOnInit调用更改为this,其中我明确声明这是一个可观察的,并将其分配给变量"records":
ngOnInit() {
const records: Observable<any> = this.clientsService.getAll(1, this.pagesize);
console.log(this.records);
}
Run Code Online (Sandbox Code Playgroud)
我还将来自RxJs的可观察导入带入了组件,如下所示:
import { Observable } from 'rxjs/Observable';
Run Code Online (Sandbox Code Playgroud)
然后在视图中我添加了异步管道,如下所示:
<tr *ngFor="let record of records.data | async">
Run Code Online (Sandbox Code Playgroud)
正如我所提到的,这是行不通的.我没有收到任何控制台错误,我只是没有看到填充到视图的任何数据.此外,在控制台中,"records"是一个空数组.
顺便说一句,我的服务"getAll"调用如下所示:
getAll(page, pagesize) {
return this.http.get
(`https://api.someurl.com/${this.ver}/clients?apikey=${this.key}&page=${page}&pagesize=${pagesize}`)
.map((response: Response) => response.json())
.catch(this.errorHandler);
}
errorHandler(error: Response) {
console.error(error);
return …Run Code Online (Sandbox Code Playgroud) 我正在构建一个简单的角度应用程序,我想要一个服务来保持一些状态.我第一次尝试这只是一个布尔记录.基本上,我想要一个导航栏组件来订阅这个值,这样当它为false时它会显示一个'login'选项,当它的true显示一个'admin'按钮时.
我的服务:
@Injectable()
export class AuthService {
private _loggedIn = new BehaviorSubject(false);
public readonly loggedIn$ = this._loggedIn.asObservable();
constructor(private http: Http, private router: Router) {
this._loggedIn = new BehaviorSubject(false);
}
public login(u: User): Observable<any> {
let obs = this.http.post(ApiRoutes.login, u).map(res => res.json());
obs.subscribe(res => {
this._loggedIn.next(res.success);
if (this._loggedIn.getValue())
this.router.navigate(['/admin']);
});
return obs;
}
}
Run Code Online (Sandbox Code Playgroud)
在我的导航组件中:
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.scss'],
providers: [AuthService]
})
export class NavComponent implements OnInit {
loggedIn: boolean;
constructor(private as: AuthService) { }
ngOnInit() {
this.as.loggedIn$.subscribe(isLoggedIn …Run Code Online (Sandbox Code Playgroud) 有没有比RxJS运算符更好的方法来循环从可观察对象返回的数组,而不是发出新的单独的ListingItem?
onGetItemData(){
this.dataService.getItemData().subscribe((itemData) =>
{
this.itemDataJSON = itemData;
this.itemDataJSON.forEach(function (value) {
let new_listing = new ListingItem(value.label,value.market,value.name);
console.log(new_listing);
});
});
}
Run Code Online (Sandbox Code Playgroud)
API返回包含项的单个数组,因此我无法使用.map访问itemData.name
//-- DataService --//
getItemData(){
return this.http.get(this._URL, { headers })
.pipe(map((res: Listings) => res.items))
}
Run Code Online (Sandbox Code Playgroud)