您好我是angular 5的新手并且跟着一些博客写了HTTP拦截器。
Asynchronously handling the file upload process
}
这很好用。但我需要做的是将此错误代码传递给其他组件,并在屏幕上为用户打印一条消息。一个人要做的就是创建一个可观察的但我无法实现它。
非常感谢任何帮助。
答案 0 :(得分:5)
您可以通过利用class Node:
def __init__(self, data,left = None,right = None):
self.data = data
self.left = left
self.right = right
class BST:
def __init__(self,root=None):
self.root = root
def insert(self,val):
new_node = Node(val)
if self.root == None:
self.root = new_node
else:
cur = self.root
leaf = None
while cur!=None:
leaf = cur
if val >= cur.data:
cur = cur.right
else:
cur = cur.left
if val >= leaf.data:
leaf.right = new_node
else:
leaf.left = new_node
def preOrder(self,root):
if root:
print(root.data,end=' ')
preOrder(root.left)
preOrder(root.right)
b = BST()
b.insert(1)
b.insert(2)
b.insert(5)
b.insert(3)
b.insert(6)
b.insert(4)
b.preOrder(b.root)
来使用服务来实现这一目标。以下是使用Subject
。
首先,您要创建一项服务。该服务将在两个类中共享:
BehaviourSubject
在export class BroadcastService {
public http404: BehaviorSubject<boolean>;
constructor() {
//initialize it to false
this.http404 = new BehaviorSubject<boolean>(false);
}
}
课程中,您将HttpInterceptor
注入其中。要更新BroadcastService
,只需使用BehvaiourSubject
:
.next()
在您的export class AngularInterceptor implements HttpInterceptor {
public http404 = false;
constructor(public broadcastService: BroadcastService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("intercepted request ... ");
// Clone the request to add the new header.
const httpReq = req.clone({
headers: req.headers.set("headerName", "headerValue")
});
console.log("Sending request with new header now ...");
//send the newly created request
return next.handle(httpReq)
.catch((error, caught) => {
//intercept the respons error and displace it to the console
console.log("Error Occurred");
if (error.status === 404)
this.http404 = true;
//need to pass this value to another component. Let's say app.component.ts and display some message to the user.
this.broadcastService.http404.next(true);
//return the error to the method that called it
return Observable.throw(error);
}) as any;
}
}
中,只需使用app.component.ts
订阅即可。你也需要注入它:
.asObservable()