Angular 2查看不显示来自Webservice的数据

时间:2022-05-25 03:52:47

I have a Web Service which is providing some user data (this is Java backend) and I have an Angular component:

我有一个提供一些用户数据的Web服务(这是Java后端),我有一个Angular组件:

import { Component,state,style,animate,transition, trigger, keyframes, 
OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/pluck';

import { IUser } from './user.interface';

@Component({
  moduleId: module.id,
  selector: 'user-cmp',
  templateUrl: 'user.component.html'
})
export class UserComponent {

  user: Observable<IUser>;

  errorMessage: string;

  constructor(private _userService: ActivatedRoute){
    this.user = _userService.data.pluck('user');
  }

}

I am using a Resolver:

我正在使用解析器:

import { Resolve } from '@angular/router';
import { Observable } from 'rxjs/Observable'
import { Observer } from 'rxjs/Observer';

import { IUser } from './user.interface';
import { UserService } from './user.service';
import {Injectable} from "@angular/core";

@Injectable()
export class UsersResolver implements Resolve<IUser> {

  constructor (private _userService: UserService) {}

  resolve(): Observable<IUser>{
    return this._userService.getUser();
  }
}

Resolver is using a service:

解析器正在使用服务:

import {Injectable} from "@angular/core";
import { Http, Response } from "@angular/http";

import { IUser } from './user.interface';

import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class UserService {
  private _userUrl = 'http://localhost:8000/rest/users';

  constructor(private _http: Http){

  }

  getUser(): Observable<IUser>{
    return this._http.get(this._userUrl)
      .map((response: Response) => {
        return <IUser> response.json();
      })
      .do(data => console.log('All: ' + JSON.stringify(data)))
      .catch(this.handleError);
  }

  private handleError (error: Response){
    console.error(error);
    return Observable.throw(error.json().error || 'Server Error');
  }
}

And finally the View:

最后是视图:

<div class="main-content" >
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8">
                <div class="card" [@carduserprofile]>
                    <div class="header">
                        <h4 class="title">Edit User Profile</h4>
                    </div>
                    <div *ngIf="user" class="content">
                        <form>
                            <div class="row">

                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>Username</label>
                                        <input type="text" class="form-control" placeholder="Username" value="{{user.username }}">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Email address</label>
                                        <input type="email" class="form-control" placeholder="Email" value="{{user.password}}">
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Phone</label>
                                        <input type="text" class="form-control" placeholder="Phone" value="{{user.telephone}}">
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label>Type</label>
                                        <input type="text" class="form-control" disabled placeholder="User type" value="{{user.type}}">
                                    </div>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-info btn-fill pull-right">Update Profile</button>
                            <div class="clearfix"></div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

The module looks like this:

该模块如下所示:

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { MODULE_COMPONENTS, MODULE_ROUTES } from './dashboard.routes';
import { UsersResolver } from './user/user.resolver';

@NgModule({
    imports: [
        BrowserModule,
        RouterModule.forChild(MODULE_ROUTES)
    ],
    declarations: [ MODULE_COMPONENTS ],
    providers: [ UsersResolver ]
})

export class DashboardModule{}

And also the part of the route is like this:

而且路线的一部分是这样的:

{ path: 'user', component: UserComponent, resolve: {user: UsersResolver} },

I didn't paste some useless parts of the code, like animations and etc. My problem is, it prints the data from the webservide using the .do in the service, but it doesn't show nothing in the View. Fields are blank.

我没有粘贴一些无用的代码部分,比如动画等。我的问题是,它使用服务中的.do从webservide打印数据,但它在View中没有显示任何内容。字段是空白的。

I am using *ngIf in case of blank user data from WS.

如果来自WS的空白用户数据,我正在使用* ngIf。

I have no idea why and also I don't know how to implement some codes to check it in the View.

我不知道为什么,也不知道如何在视图中实现一些代码来检查它。

Any help will be great! Thanks in advance.

任何帮助都会很棒!提前致谢。

1 个解决方案

#1


3  

The problem I see is located here:

我看到的问题是在这里:

constructor(private _userService: ActivatedRoute){
  this.user = _userService.data.pluck('user');
}

this.user is an observable so you need to subscribe it to get the value either within the component (with this.user.subscribe(...)) or in the template using the async pipe.

this.user是一个observable,因此您需要订阅它以获取组件内的值(使用this.user.subscribe(...))或使用异步管道在模板中获取值。

Perhaps you could simply leverage the snapshot for the route:

也许您可以简单地利用路径的快照:

constructor(private _userService: ActivatedRoute){
  this.user = _userService.snapshot.data['user'];
}

This way the user would be a raw JS object and not an observable. So using the following should be better:

这样,用户将是原始JS对象而不是可观察对象。所以使用以下应该更好:

<div *ngIf="user" class="content">

#1


3  

The problem I see is located here:

我看到的问题是在这里:

constructor(private _userService: ActivatedRoute){
  this.user = _userService.data.pluck('user');
}

this.user is an observable so you need to subscribe it to get the value either within the component (with this.user.subscribe(...)) or in the template using the async pipe.

this.user是一个observable,因此您需要订阅它以获取组件内的值(使用this.user.subscribe(...))或使用异步管道在模板中获取值。

Perhaps you could simply leverage the snapshot for the route:

也许您可以简单地利用路径的快照:

constructor(private _userService: ActivatedRoute){
  this.user = _userService.snapshot.data['user'];
}

This way the user would be a raw JS object and not an observable. So using the following should be better:

这样,用户将是原始JS对象而不是可观察对象。所以使用以下应该更好:

<div *ngIf="user" class="content">