I have a problem loading the user data into the page. I get this Error: GET http://localhost/ 401 (Unauthorized).
In Laravel I've put this into my controller to get all user data:
public function index()
{
$user = User::all(); return response()->json($user,201);
}
In Angular I've created a data.service file with this code:
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
findAll(): Observable<User[]>{return this.http.get<User[]>('http://localhost');}
}
And In the app.component.ts file, I used this method to get the data:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
users$: User[];
constructor(private dataService: DataService){}
ngOnInit(){return this.dataService.findAll().subscribe(data => this.users$ = data);}
}
In the app.component.html file I've looped through the data:
<div *ngFor='let user of users$'>{{user.name}}</div>
Is this an error returned by angular or laravel? Also please note the following:
Here is the better solution:
export class AppComponent implements OnInit{
users$: Observable<User[]>;
constructor(private dataService: DataService){}
ngOnInit(){
this.user$ = this.dataService.findAll()
}
}
and in HTML keep your current code as it is:
<div *ngFor='let user of users$'>{{user.name}}</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.