如何在角度CLI中接收当前路由响应?

时间:2018-02-14 08:28:17

标签: node.js angular angular-cli angular-components

对于单个应用程序使用angualar cli和nodejs,在nodejs中配置的passportjs,node给出用户数据并返回带有角度端口的Object,如何在ngOnInit()的角度路径中接收此响应?

重定向网址:http://localhost:4200/api/pauth?code=4%2FAAAOF7UrUC...

我在角度/api/pauth中也有相同的路径来访问数据。

对上述网址的响应(来自nodejs):

{"status":"0","message":"Looged in successfully","user":{"_id":"5a797783cb91253f8c667232","email":"example@gmail.com","password":"ya9.GltZBYvinL7N6D6OvgQ1z2Poa7ceOO3TS7LQB-CcsT3","authType":"google","createdAt":"2018-02-06T09:38:11.965Z","updatedAt":"2018-02-06T09:38:11.965Z","__v":0}}

component.ts:

constructor(private http:Http, private router:Router,private httpc: HttpClient) { }

ngOnInit() {
    console.log(this.router.url);
    this.http.get(this.router.url).subscribe(res => {
      this.posts = res;
      console.log(this.posts);
    });
}

2 个答案:

答案 0 :(得分:0)

我将使用httpclient告诉解决方案,我希望您在app.module.ts中导入httpclient模块

constructor(private http: HttpClient) {
   let headers = new HttpHeaders({'Content-Type': 'application/json' });
   this.options =headers;
}
ngOninit(){
   this.getdata().subscribe(data=>{console.log(data)})
}
getdata(){
   this.http.get<any>(url,
     {headers:this.options,responseType:"json",observe:"response"})
     .map(res =>res.body)
}

答案 1 :(得分:0)

替代解决方案:

当两个端口混合时无法访问对象响应,需要使用params从Node JS重定向,现在能够处理角度路由。

来自节点的示例 - api.js

{{1}}