node.js - Angular2 将参数传递给 web 服务 http GET

标签 node.js rest http angular

我有一个 profileComponent,它正在对服务端点进行 GET 调用,如下所示,AparmentService 被注入(inject)到 bootstarp 中,因此没有提供者

@Component({
    selector: 'profile',
    template: `<h1>Profile Page</h1>

 {{userEmail.email}}
 {{profileObject | json}}
 `,
    directives: [ROUTER_DIRECTIVES]    
})

export class ProfileComponent implements OnInit {
    userEmail = JSON.parse(localStorage.getItem('profile'));
    public profileObject: Object[];


    constructor(private apartmentService: ApartmentService) { 
        this.apartmentService = apartmentService;
    }

    ngOnInit(): any {
        console.log(this.userEmail.email);                <--This value displays fine in the console 
        this.apartmentService.getProfile(this.userEmail.email).subscribe(res => this.profileObject = res);  <-- getting [] response for this 
        console.log(JSON.stringify(this.profileObject));   <-- undefined         
    }
}

服务看起来像这样

@Injectable()
export class ApartmentService {

    http: Http;
    constructor(http: Http) {
        this.http = http;
    }

    getProfile(userEmail :string){
       return this.http.get('/api/apartments/getprofile/:userEmail').map((res: Response) => res.json());
    } 
}

当我尝试使用参数直接在浏览器中访问端点时,我得到了响应。但不在 Angular 中。

有什么想法吗?

最佳答案

http.get() 是异步的

ngOnInit(): any {
    console.log(this.userEmail.email);                <--This value displays fine in the console 
    this.apartmentService.getProfile(this.userEmail.email).subscribe(res => this.profileObject = res);  <-- getting [] response for this 
    // at this position the call to the server hasn't been made yet.
    console.log(JSON.stringify(this.profileObject));   <-- undefined         
}

当来自服务器的响应到达时 res => this.profileObject = res 被执行。 console.log() 在对服务器的调用甚至被初始化之前进行

改用

ngOnInit(): any {
    console.log(this.userEmail.email);                <--This value displays fine in the console 
    this.apartmentService.getProfile(this.userEmail.email)
    .subscribe(res => {
      this.profileObject = res; 
      console.log(JSON.stringify(this.profileObject));
    });
}

我认为 URL 中的 :userEmail 没有达到您的预期。试试看:

getProfile(userEmail :string){
   return this.http.get(`/api/apartments/getprofile/${userEmail}`).map((res: Response) => res.json());
} 

关于node.js - Angular2 将参数传递给 web 服务 http GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37474804/

相关文章:

android - 如何在 flutter POST 中发送请求编码为 :null ? 的二进制加密数据;它在 Node js 中正常工作

javascript - 在 Socket.io 中排除发射

javascript - 如何使用 GET 方法访问 RESTlet SuiteScript 参数

java - 构建 REST Angular 应用程序的正确方法是什么?

javascript - 由于请求的资源上不存在 'Access-Control-Allow-Origin' header ,无法获取与 Axios 的链接请求

node.js - Yo Webapp : Error EACCES, 权限被拒绝 'Gruntfile.js'

javascript - 在 Windows 中查找 Node.js 服务器的进程 ID

android - Windows 和 Android 应用程序是否需要 SSL?

java - 如何通过局域网发出 HTTP 请求?

java - 将 cURL 命令转换为纯 Java