Angular 2在加载子组件之前获取数据

时间:2016-12-29 08:58:18

标签: angular

我希望在应用程序的主根组件中获取用户数据,然后将用户数据存储到服务中以继续加载其他组件。我怎样才能做到这一点?目前,我有这样的事情:

@Injectable()
export class UserService {

user: Subject<User> = new BehaviorSubject(new User());

constructor(private _httpService: HTTPService){}

getUser(){
    return this.user;
}

getUserFromAPI(){
    this._httpService.get('user')
        .map(data => data.json())
        .subscribe(data => {
            this.user.next(data);
        });
}

但是通过这种方式,这意味着我需要通过我不想要的Observable将用户放在其他每个地方。我想要一个静态访问。 目前,我正在收到用户:

this._userService.getUser().subscribe(data => {
        this.user = data;
    });

1 个答案:

答案 0 :(得分:1)

您可以使用private final int GALLERY_REQUEST = 0; Uri imageUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent pictureActionIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(pictureActionIntent, GALLERY_REQUEST); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case GALLERY_REQUEST: if (data != null) { imageUri = data.getData(); Bitmap image = null; Bitmap modified_img_bitmap = null; ImageView picked_image = (ImageView)findViewById(R.id.imageView); ParcelFileDescriptor percelFileDescriptor; Toast.makeText(getApplicationContext(),""+imageUri.toString(),Toast.LENGTH_LONG).show(); try { percelFileDescriptor = getContentResolver().openFileDescriptor(imageUri, "r"); image = BitmapFactory.decodeFileDescriptor(percelFileDescriptor.getFileDescriptor()); modified_img_bitmap = image; percelFileDescriptor.close(); picked_image.setImageBitmap(image); } catch (FileNotFoundException e) { System.out.println("File Not Found: " + e.toString()); Toast.makeText(getApplicationContext(),"File not found: "+e.toString(),Toast.LENGTH_LONG).show(); } catch (IOException e) { Toast.makeText(getApplicationContext(),"IO Error: "+e.toString(),Toast.LENGTH_LONG).show(); System.out.println("IO Exception: " + e.toString()); } } break; default: break; } } } Angularjs2 - preload server configuration before the application starts让Angular在数据可用之前等待呈现任何组件

或者您可以使用APP_INITIALIZER来阻止在数据可用之前呈现组件

*ngIf