我有一个通常http intercetor
,它调用某个API,如果收到403
响应,则必须发出一个事件。
拦截器:
@Injectable
export class CustomHttpInterceptor implements HttpInterceptor {
@Output() notify: EventEmitter<boolean> = new EventEmitter<boolean>();
constructor() {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.body.status === 403) {
this.notify.emit(true);
}
return next.handle(req);
}
}
然后我有一个navi.component.html
会听这个事件:
<md-toolbar (notify)="onNotify($event)">
<a routerLink="/home">
<img src="assets/images/logo.png" class="md-card-image p-navi-logo" alt="image caption"></a>
<span class="spacer"></span>
<div fxLayout="row" fxShow="false" fxShow.gt-sm>
<development *ngIf="isLoggedIn"></development>
<guide-menu></guide-menu>
<documentation-menu></documentation-menu>
<administration *ngIf="isAdmin"></administration>
<about></about>
</div>
...
top-navi.component.ts
public onNotify(result: boolean):void {
console.log('notification received: ' + result);
this.isLoggedIn = result;
}
问题是top-navi-component永远不会得到事件而且没有记录任何事情。我做错了什么?
答案 0 :(得分:5)
尝试按照以下步骤
发出值如果您使用现有服务文件
,请创建新服务文件@Injectable()
export class SampleService {
notify: Subject<boolean> = new Subject<boolean>();
onNotify(event) {
this.notify.next(true);
}
}
<强> sample.service.ts 强>
@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
constructor(private sampleService: SampleService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.body.status === 403) {
this.sampleService.onNotify(true)
}
return next.handle(req);
}
}
<强>拦截器:强>
<md-toolbar>
<a routerLink="/home">
<img src="assets/images/logo.png" class="md-card-image p-navi-logo" alt="image caption">
</a>
<span class="spacer"></span>
<div fxLayout="row" fxShow="false" fxShow.gt-sm>
<development *ngIf="isLoggedIn"></development>
<guide-menu></guide-menu>
<documentation-menu></documentation-menu>
<administration *ngIf="isAdmin"></administration>
<about></about>
</div>
</md-toolbar>
和 navi.component.html
export class TopNaviComponent {
constructor(private sampleService: SampleService) {
this.sampleService.notify.subscribe((result) => {
console.log('result', result)
})
}
}
最后 top-navi.component.ts
word = "nonagon"
wordlist=[]
blanks=[]
for i in word:
wordlist.append(i)
blanks.append("-")
attempts = 10
while attempts != 0:
guess = input("Take a guess: ")
for i in wordlist:
if i == guess:
blanks[wordlist.index(i)]=guess
attempts-=1
print(blanks)